Search Insert Position Solution
Given a sorted array and a target, return the index if found โ or the index where it would be inserted.
Problem Statement
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be inserted to keep the array sorted. You must write an O(log n) algorithm.
Linear Scan โ O(n)
Walk through the array. Return the first index where nums[i] >= target. If no such index, insert at the end.
nums[i] >= target.
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(1) |
Binary Search (Lower Bound) โ O(log n)
This is the classic lower bound binary search. Find the leftmost position where the target could be inserted. When nums[mid] < target, move right. Otherwise, the answer is at mid or earlier โ move left boundary.
left is exactly where you sit (or insert).
- Step 1:
left = 0,right = n(note: not n-1, because insert position could be past the end). - Step 2: While
left < right: compute mid. - Step 3: If
nums[mid] < targetโleft = mid + 1. - Step 4: Else โ
right = mid. - Step 5: Return
left.
- Standard binary search returns -1 if not found. Lower bound always returns a valid insert position.
- The difference: use
left < right(not โค) andright = mid(not mid-1). - This converges L and R to the insertion point.
- This is equivalent to C++
std::lower_boundor Python'sbisect.bisect_left.
Visual Walkthrough
Trace through nums = [1, 3, 5, 6], target = 2:
Code โ Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Linear Scan | O(n) | O(1) | Simple but ignores sorted |
| Lower Bound BS โ optimal | O(log n) | O(1) | Classic lower-bound search |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Insert at start | [2,4,6], target=1 | All elements โฅ target โ left stays 0 โ insert at 0. |
| Insert at end | [2,4,6], target=7 | All elements < target โ left reaches n โ insert at end. |
| Exact match | [2,4,6], target=4 | Found โ return index 1. Lower bound naturally finds it. |
| Single element | [3], target=3 | mid=0, nums[0]=3 โฅ 3 โ R=0 โ L==R==0. |
right = n - 1 instead of right = n. The insert position can be at index n (past the end), so the search range must include it. With right = n - 1, inserting after the last element is missed.