Search Insert Position
The insight: binary search doesn't just locate an exact match — the way it narrows left and right also pins down exactly where the value would go if it were missing. Every time nums[mid] is too small, left moves past it, so everything before the new left is provably smaller than the target; every time nums[mid] is too big, right moves before it, so everything after the new right is provably bigger. When the loop ends, left sits exactly on the boundary between "too small" and "too big" — that boundary IS the insertion point, whether or not the target was actually present. This trace shows the case where target=5 IS found at index 2, short-circuiting the loop before it ever needs to fall back on that boundary.
Details
Animated on: 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 if inserted in order.
Problem:Search Insert PositionEasy
Pattern:Binary Search on Sorted Data
Binary Search
step 1 / 6
Initialize left=0 and right=3 (last index of nums).
- left=0· arr[0] = 1
- right=3· arr[3] = 6
1FUNCTION searchInsert(nums, target):2 left = 0, right = the length of nums - 13 WHILE left <= right:4 mid = (left + right) / 2, rounded down5 IF nums[mid] === target: RETURN mid6 IF nums[mid] < target: left = mid + 17 ELSE: right = mid - 18 END WHILE9 RETURN left10END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 6 steps
- Initialize left=0 and right=3 (last index of nums).
- Compute mid = floor((0+3)/2) = 1.
- nums[1] = 3 < target 5. Since 3 < 5, move left past mid: left = mid + 1 = 2.
- Compute mid = floor((2+3)/2) = 2.
- nums[2] = 5 === target. Found at index 2!
- Return mid=2 directly — the target 5 is found at index 2. (If it weren't present, the loop would instead exit and 'return left' — the natural insertion point.)
Now solve it yourself
Watching is the first half. The second is writing it without the animation.