Binary Search
Discard half the candidates per comparison for O(log n) lookups.
The idea
Binary search repeatedly probes the middle of a sorted range and uses the ordering to throw away the half that cannot contain the answer. Twenty comparisons suffice to pinpoint one item among a million.
The deeper skill is 'binary search on the answer': whenever a predicate is monotonic (false, false, …, true, true), you can binary-search for the boundary even when there is no literal sorted array — think minimum feasible capacity, earliest valid time, or smallest k that works.
Guessing a number between 1 and 100. Each guess of the midpoint and a 'higher / lower' reply halves the range — you home in within seven guesses.
When to reach for it
- The data (or the answer space) is sorted / monotonic.
- You need a value, a boundary, or a first/last position.
- A linear scan is too slow for the input size.
Language-independent template
lo, hi = 0, n - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if check(mid): return mid
elif tooSmall(mid): lo = mid + 1
else: hi = mid - 1Complexity — time O(log n), space O(1).
Common mistakes
- Computing
mid = (lo + hi) / 2and overflowing — preferlo + (hi - lo) / 2. - Inconsistent bounds causing an infinite loop (mixing inclusive/exclusive
hi). - Using
<vs<=incorrectly for the loop condition.
Practice progression
Canonical interview problems, ordered from foundation to advanced application.
Return a target's index in a sorted array or -1.
Find a target in a rotated array in logarithmic time.
Find the combined median in logarithmic time.