Search Insert Position (LeetCode 35): Solution and Explanation
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).
Watch it run step by step
Try your own input and write the code →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
- Set
left = 0andright = len(nums) - 1. - While
left <= right, computemid = (left + right) // 2. - If
nums[mid]equals the target, returnmid. - If
nums[mid]is smaller than the target, the insert point is to the right, so setleft = mid + 1. - Otherwise set
right = mid - 1. - 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
- Start with
left = 0andright = 3.mid = 1holds 3, which is larger than 2, sorightbecomes 0. mid = 0holds 1, which is smaller than 2, soleftbecomes 1.- Now
left = 1exceedsright = 0, so the loop stops. - 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 left1class Solution {
2 public int searchInsert(int[] nums, int target) {
3 int left = 0, right = nums.length - 1;
4
5 while (left <= right) {
6 int mid = (left + right) / 2;
7 if (nums[mid] == target) return mid;
8 else if (nums[mid] < target) left = mid + 1;
9 else right = mid - 1;
10 }
11
12 return left;
13 }
14}1class Solution {
2public:
3 int searchInsert(vector<int>& nums, int target) {
4 int left = 0, right = nums.size() - 1;
5
6 while (left <= right) {
7 int mid = (left + right) / 2;
8 if (nums[mid] == target) return mid;
9 else if (nums[mid] < target) left = mid + 1;
10 else right = mid - 1;
11 }
12
13 return left;
14 }
15};Time and space complexity
O(log n)
Each iteration halves the range between left and right, so at most about log₂ n iterations run.
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
rightormidafter the loop.rightends one position before the insert point, andmiddepends on the last comparison. - Forgetting the case where the target is larger than every element. The answer is
len(nums), whichleftnaturally reaches. - Writing
while left < rightwhile also usingright = mid - 1. Mixing the two binary search templates can skip the final candidate. - Computing
midas(left + right) / 2in Java or C++ with huge indices, which can overflow.left + (right - left) / 2is 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.