We are given a sorted array of distinct integers and a target value. We need to return the index if the target is found. If not, return the index where it would be if it were inserted in order. The constraint runtime complexity immediately screams Binary Search.
The algorithm is a standard binary search:
- Maintain two pointers,
leftandright. - Calculate the
midpointer. - Compare
nums[mid]totarget. - If they match, return
mid. - If
nums[mid] < target, the target must be to the right, soleft = mid + 1. - If
nums[mid] > target, the target must be to the left, soright = mid - 1.
The “Trick”: What happens if the element is not found?
When the while left <= right loop terminates without finding the target, the pointers have crossed. At this exact moment, left will inherently be pointing to the exact index where the target should be inserted. Why? Because the loop exits when left > right. The final move before exiting was either:
leftmoving pastright(target is greater thannums[right], so it belongs atright + 1which isleft).rightmoving belowleft(target is less thannums[left], so it belongs atleft). In either case,leftis the correct insertion index.
Pseudocode:
l = 0, r = len(nums) - 1
while l <= r:
mid = l + (r - l) / 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
l = mid + 1
else:
r = mid - 1
return lC++ Code:
#include <vector>
class Solution {
public:
int searchInsert(std::vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
// Prevents integer overflow in C++
int mid = l + (r - l) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return l;
}
};- Time Complexity: . Standard binary search halves the search space at each step.
- Space Complexity: . We only use a few variables for pointers (
l,r,mid).
- Target is smaller than all elements: The
rpointer will keep shifting left untilr = -1. The loop breaks, andlis0. Correct, it belongs at the start. - Target is larger than all elements: The
lpointer will keep shifting right until it equalslen(nums). The loop breaks, andlis returned. Correct, it belongs at the very end. - Empty Array: If given (though constraints say length >= 1),
l=0,r=-1. Loop doesn’t run, returns0.
- Thought Process & Recognition: “Sorted Array” + “Find/Search” + “O(log N)” = Binary Search. It’s the most literal translation of the pattern possible.
- Mental Model for Insertion: A great way to visualize why
return lworks is to imagine binary search as zooming in on a gap between two numbers. When the search space narrows to zero (pointers cross),leftalways lands on the first element greater than the target. Thus, pushing that element (and everything after it) to the right to make room means the new element takesleft’s index!