Binary Search
Signal: sorted data, "find the first/last position where…", "minimum value such that…", O(log n) expected, or a search space of possible answers with a monotonic yes/no test.
Core idea: if a predicate is monotonic over the search space (false, false, …, false, true, true, …), you can find the boundary by testing the middle and discarding half each step: O(log n).
One template to rule them all
Find the first index where ok(i) is true in [lo, hi]:
python
def first_true(lo, hi, ok):
while lo < hi:
mid = (lo + hi) // 2 # lower middle
if ok(mid):
hi = mid # mid might be the answer; keep it
else:
lo = mid + 1 # mid is definitely not the answer
return lo # lo == hi == first true (if any)- Searching sorted arrays:
ok(i) = a[i] >= targetgives the insertion point (bisect_left). - Binary search on the answer:
ok(x) = "can we finish with capacity/speed/time x?", as in Koko Eating Bananas, shipping capacity, or splitting arrays.
Classic bugs
- Infinite loop: using
lo = midwith a lower middle. Pairhi = midwithlo = mid + 1. - Overflow in fixed-width languages: write
mid = lo + (hi − lo) / 2. - Off-by-one in
hi: decide whetherhiis inclusive (while lo <= hi) or exclusive (while lo < hi) and stay consistent.