Visualize

Pattern visualizer

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. 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..

Binary Search

time O(log n)space O(1)step 1 / 6
1
[0]
3
[1]
5
[2]
6
[3]
line 2

Initialize left=0 and right=3 (last index of nums).

Pseudocode
1FUNCTION searchInsert(nums, target):
2 left = 0, right = the length of nums - 1
3 WHILE left <= right:
4 mid = (left + right) / 2, rounded down
5 IF nums[mid] === target: RETURN mid
6 IF nums[mid] < target: left = mid + 1
7 ELSE: right = mid - 1
8 END WHILE
9 RETURN left
10END FUNCTION

← / → step · space play · Home restart

Where to practice Binary Search