AlgoViz

Binary search

easy 16 min

Binary search finds a value, a boundary or an insertion point in sorted data by checking the middle and discarding the half that cannot hold the answer.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Look in the middle, throw away the half that cannot hold it, repeat.

Looking up Smith in a phone book. You open it near the middle, land on M, and know Smith is in the second half. You never look at the first half again. Open the middle of what is left, and in a few looks you are on the right page.

Binary search in one picture

Cheat sheet

Time
O(log n), at most floor(log2 n) + 1 comparisons
Space
O(1) iterative, O(log n) recursive
Needs
sorted data or a monotonic test, random access
Midpoint
left + (right - left) // 2
Closed loop
right = n - 1, while left <= right, mid ± 1
Half-open loop
right = n, while left < right, right = mid
Lower bound
first index with value >= x (bisect_left)
Upper bound
first index with value > x (bisect_right)
Million items
20 comparisons

Spot it when you see

  • The input is sorted and you need a value, boundary or insertion point.
  • First or last position of a value, or how many times it appears.
  • Minimise the maximum or maximise the minimum.
  • A question of the form: is X enough? whose answer flips once.
  • A rotated sorted array, or find any peak.
  • O(n) is too slow and the constraints hint at O(log n).

Tricks that stick

  • LIMP: Loop while left <= right, Index of the middle, Match against the target, move a Pointer.
  • Go to the middle, make a compare. Too big? Go left. Too small? Go there. Halve the space with every try, log n steps and you are done.
  • Hot or cold: guess the middle of the room, ignore the cold half, guess the middle of the warm half.
  • Double the data, add one step.
  • First occurrence: save and go left. Last occurrence: save and go right.
  • Count of x is upper bound minus lower bound.

Do not forget

  • Using (left + right) // 2 in Java or C++: overflow.
  • Using < with right = n - 1: the last candidate is skipped.
  • Using <= with right = n: index out of range.
  • Setting left = mid with a floor midpoint: infinite loop.
  • Returning on the first match when the first or last copy is needed.
  • Running it on unsorted data or a linked list.