PPractick

DSA interview question

Search Insert Position

Easy · Algorithms · Topics: binary search, array

The problem

A leaderboard keeps its scores in a sorted array with no duplicates. When a player finishes a game, the app must either find their score if it's already listed or report the index where it would be inserted to keep the list sorted, so the new entry can be animated into place. That position is exactly the lower bound of the score: the first index whose value is at least the target. One binary search answers both "is it here?" and "where would it go?".

Example: [1, 3, 5, 6], target 2 → 1 (it would go between 1 and 3).

Function signature

int searchInsert(const vector<int>& nums, int target);  // index of target, or where it would be inserted

Test cases

Input (nums, target)OutputExplanation
([1, 3, 5, 6], 5)2Found at index 2
([1, 3, 5, 6], 2)1Would go before 3
([1, 3, 5, 6], 7)4Larger than everything: append at the end
([1, 3, 5, 6], 0)0Smaller than everything
([1], 1)0
([], 3)0Empty array

(Confirm: the array is sorted with distinct values; O(log n) is expected.)

How interviewers phrase it

Clarifying questions to ask

  1. Are the values distinct?
  2. If the target is found, should I return its index? (Yes.)
  3. Is O(log n) required?

Follow-ups to expect

  1. "Why is this just lower bound?"
  2. "What if the array had duplicates?"
  3. "Library equivalent?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in