Search Insert Position (LeetCode 35): Solution and Explanation

Easy
Array
Binary Search

You are given a sorted array of distinct integers and a target. Return the target's index if it is present; if not, return the index where it would have to be inserted to keep the array sorted. The expected run time is O(log n).

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The linear way is to walk the array and return the first index whose value is at least the target, or the array length if no such value exists. That is correct and covers both cases at once, but it is O(n).

Since the array is sorted, binary search gets you to O(log n). The found case is ordinary binary search. The interesting part is what happens when the target is missing. The loop keeps an invariant: every index left of left holds a value smaller than the target, and every index right of right holds a value larger. When the loop ends, left is exactly one past right, so left points at the first element larger than the target, or at the end of the array.

That first larger position is precisely where the target belongs. So the same loop handles both cases: return mid on a match, and return left after the loop otherwise. In other words, this problem is the lower-bound search in disguise, and recognizing that saves you from special-casing targets that fall before the first element or after the last one.

It is worth checking the two edge cases by hand. If the target is smaller than everything, right keeps shrinking until it reaches -1 and left stays at 0, so the answer is 0. If it is larger than everything, left keeps growing until it equals the array length, which is the position just past the last element. No extra branches are needed for either case.

Approach: Binary search returning the lower bound

  1. Set left = 0 and right = len(nums) - 1.
  2. While left <= right, compute mid = (left + right) // 2.
  3. If nums[mid] equals the target, return mid.
  4. If nums[mid] is smaller than the target, the insert point is to the right, so set left = mid + 1.
  5. Otherwise set right = mid - 1.
  6. When the loop exits, return left, which is the first index whose value exceeds the target.

Step-by-step example

nums = [1,3,5,6], target = 2
  1. Start with left = 0 and right = 3. mid = 1 holds 3, which is larger than 2, so right becomes 0.
  2. mid = 0 holds 1, which is smaller than 2, so left becomes 1.
  3. Now left = 1 exceeds right = 0, so the loop stops.
  4. The function returns 1. Inserting 2 at index 1 gives [1, 2, 3, 5, 6], which is still sorted.

Code: Python, Java, C++

1class Solution:
2    def searchInsert(self, nums: List[int], target: int) -> int:
3        left, right = 0, len(nums) - 1
4
5        while left <= right:
6            mid = (left + right) // 2
7            if nums[mid] == target:
8                return mid
9            elif nums[mid] < target:
10                left = mid + 1
11            else:
12                right = mid - 1
13
14        return left

Time and space complexity

Time

O(log n)

Each iteration halves the range between left and right, so at most about log₂ n iterations run.

Space

O(1)

Only the two pointers and mid are stored.

Other approaches

Library lower bound (time O(log n), space O(1))

Python's bisect_left(nums, target) and C++'s lower_bound return exactly this index. It is the cleanest production answer, but interviewers usually want to see the loop.

Linear scan (time O(n), space O(1))

Return the first index whose value is at least the target, or len(nums) if none is. It is simple and fine for tiny arrays but does not meet the logarithmic requirement.

Common mistakes

  • Returning right or mid after the loop. right ends one position before the insert point, and mid depends on the last comparison.
  • Forgetting the case where the target is larger than every element. The answer is len(nums), which left naturally reaches.
  • Writing while left < right while also using right = mid - 1. Mixing the two binary search templates can skip the final candidate.
  • Computing mid as (left + right) / 2 in Java or C++ with huge indices, which can overflow. left + (right - left) / 2 is safe; Python does not have this issue.

Frequently asked questions

Why does returning left give the insert position?

Throughout the loop, everything before left is smaller than the target and everything after right is larger. When they cross, left is the first position holding a larger value, so inserting there keeps the order.

Is Search Insert Position the same as lower bound?

Yes. Because the values are distinct, the index of the target if it exists and the insert position if it does not are both the first index whose value is at least the target, which is the definition of lower bound.

What if the array has duplicates?

The problem guarantees distinct values. With duplicates, this loop may return any matching index, so you would use a pure lower-bound search that keeps moving left on a match to get the first one.

What is the time complexity of Search Insert Position?

It is O(log n) time and O(1) space, since each step halves the search range.