Search Insert Position solution explained
Search Insert Position asks for the index of a target in a sorted array, or the index where it would be inserted to keep the array sorted if it is missing. Both answers are the same thing: the first index whose value is at least the target, often called the lower bound. A binary search over the half-open range [lo, hi) finds it in O(log n) time and O(1) memory.
By Evin JohnPublished 8 min read
The problem, restated
You have a list of numbers in increasing order with no repeats, and one more number. If the number is in the list, return its position. If it is not, return the position it would occupy if you slipped it in without breaking the order. Positions start at 0. The expected running time is logarithmic, which rules out walking the list.
| Target | Answer | Why |
|---|---|---|
| 12 | 2 | Found at index 2 |
| 10 | 2 | It belongs between 8 and 12 |
| 1 | 0 | Smaller than everything, so it goes first |
| 25 | 4 | Larger than everything, so it goes at the end |
| 5, in an empty array | 0 | The only place to put it |
Why such an easy problem gets asked
Binary search is short and famously easy to get subtly wrong: an off-by-one in the bounds, a loop that never ends when two elements remain, or a wrong return value when the target is missing. This problem is a clean test of whether you can write a correct binary search from first principles and explain why it terminates and why the returned index is right. It often appears as a warm-up before a harder problem that uses the same search.
Follow-ups
- The array has duplicates; return the first occurrence. The lower bound already does that; no change needed.
- Return the last occurrence, or where to insert after equal values. Change the comparison to less-than-or-equal, which gives the upper bound.
- Count how many times the target appears. Upper bound minus lower bound.
- The array is rotated. You need an extra comparison against one end to decide which half is sorted; a different problem with the same skeleton.
Brute force
Walk from the left and return the first index whose value is at least the target, or the array length if none is. That is O(n), correct, and a useful sentence to say before the faster version, because it states precisely what you are looking for: the first position where a yes-or-no question flips from no to yes.
The optimal approach: lower bound with a clear invariant
Keep two indexes with a promise attached. Everything before lo is smaller than the target. Everything at hi or after is at least the target. At the start nothing is known, so lo is 0 and hi is the length of the array, one past the end. Look at the middle index between them. If its value is smaller than the target, the middle and everything before it are too small, so move lo to mid + 1. Otherwise the middle is a candidate, so move hi to mid. Each step shrinks the gap, and when lo equals hi the promise says that index is the first one at least the target.
def search_insert(nums, target):
lo, hi = 0, len(nums) # answer is somewhere in [lo, hi]
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < target:
lo = mid + 1 # nums[mid] and everything left of it are too small
else:
hi = mid # nums[mid] is a candidate
return lofunction searchInsert(nums, target) {
let lo = 0;
let hi = nums.length;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}Trace 10 in [3, 8, 12, 20]. lo 0, hi 4, mid 2: 12 is not smaller, so hi becomes 2. mid 1: 8 is smaller, so lo becomes 2. lo equals hi, return 2. Trace 25: mid 2 then mid 3, both smaller, lo becomes 4 and the loop ends with 4, one past the end, which is the right insertion point. hi started at the length precisely so that this answer is reachable.
Why it always stops
While lo is below hi, mid is at least lo and strictly below hi, because the division rounds down. So lo = mid + 1 raises lo, and hi = mid lowers hi; the gap shrinks by at least one every time, usually by about half. A version that sets lo = mid instead can get stuck when lo and hi are adjacent, which is the most common infinite loop in binary search.
The midpoint in other languages
In Python, integers do not overflow, so (lo + hi) // 2 is fine. In Java, C++ or C#, lo + hi can exceed the largest int for very large arrays, so the safer habit is lo + (hi - lo) / 2, which the JavaScript version above also uses for consistency. Mentioning this unprompted is a small point in your favor.
The closed-range version
Many people learned binary search with lo and hi both inclusive. That works too, as long as the loop condition, the updates and the return match. With a closed range the loop runs while lo is at most hi, both sides move past mid, and lo ends one past the last element that was too small, which is again the insertion point.
def search_insert_closed(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return lo # every index before lo holds a smaller valuePick one style and use it every time. Mixing them, for example a closed loop condition with a half-open update, is how most binary search bugs are born. If the array may contain duplicates and you need the first match, the half-open version is the safer one, because the closed version above returns whichever equal element the search happens to land on.
Using the library
from bisect import bisect_left
def search_insert_bisect(nums, target):
return bisect_left(nums, target)In C++ the equivalent is std::lower_bound. It is fine to mention the library, and in production code you should use it, but in an interview write the loop unless told otherwise.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Linear scan | O(n) | O(1) |
| Binary search, half-open range | O(log n) | O(1) |
| Binary search, closed range | O(log n) | O(1) |
| bisect_left or std::lower_bound | O(log n) | O(1) |
Edge cases
- Empty array: 0.
- Target below the first element: 0.
- Target above the last element: the array length.
- Target equal to the first or last element.
- A single-element array, with the target below, equal to and above that element.
A good way to test a binary search is to try every possible target position: for an array of length n there are n + 1 insertion points plus n exact matches, and a small array covers all of them in a few seconds of hand tracing.
Common mistakes
- Starting hi at len - 1 in the half-open version, which makes the end position unreachable.
- Writing lo = mid instead of lo = mid + 1, which can loop forever on two elements.
- Returning -1 when the target is missing, as in a plain search, instead of the insertion point.
- Returning mid or hi after a closed-range loop instead of lo.
- Computing (lo + hi) / 2 without integer division in a language that produces a fraction.
How to explain it out loud
Fictional example
- Candidate
- Found or not, the answer is the number of elements smaller than the target, which is the first index holding something at least the target. That is a lower bound.
- Candidate
- I keep lo and hi so that everything before lo is too small and everything from hi on is big enough. I start at 0 and the length, so inserting at the end is possible.
- Candidate
- If the middle value is too small I move lo past it, otherwise I pull hi down to it. The gap shrinks every step, and when lo meets hi that is the answer. Log n time, constant memory.
Related problems
Sqrt(x) uses the same first-true search over a range of candidate answers instead of array positions. Kth Smallest Element in a Sorted Matrix applies it to values, with a counting function as the test. Two Sum is a good contrast: on a sorted array it can use two pointers, while the unsorted version uses a hash map.
Practicing with Natively
Since the code is short, practice the explanation of the invariant until it comes out in two sentences. On Mac or Windows, Natively can read the problem from a screenshot during practice and suggest a search setup to compare with your own afterward, and the transcript of your mock shows whether you said why the loop terminates. More about the AI interview assistant.
Questions people ask
How do you solve Search Insert Position?
Binary search for the first index whose value is at least the target. Keep lo = 0 and hi = the array length; if the middle value is smaller than the target set lo = mid + 1, otherwise hi = mid; return lo when they meet.
What is the time complexity of Search Insert Position?
O(log n) time and O(1) extra memory, because each step halves the range of possible answers.
Why does hi start at the array length instead of the last index?
The target may belong after every element, so the answer can be the length itself. Starting hi one past the end keeps that answer reachable in the half-open version.
Is Search Insert Position the same as lower bound?
Yes. Both return the first position whose value is at least the target, which equals the number of elements smaller than it. Python's bisect_left and C++'s std::lower_bound compute it.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
