Binary Search
Binary search turns an O(n) scan into O(log n), but only when you can look at one position and say which side the answer is on. It is not just for “find x in a sorted array”. It works on any space where a yes/no test flips exactly once.
When to reach for it
Section titled “When to reach for it”- The input is sorted, or sorted-but-rotated, and you need O(log n).
- You are asked for the smallest/largest value that satisfies a condition (minimum speed, minimum capacity, first bad version).
- The condition is monotonic: false, false, false, true, true, true. Once true, it stays true.
- Brute force tries every candidate answer and checks each one.
Template
Section titled “Template”lo, hi = 0, len(nums) - 1 # inclusive range [lo, hi]while lo <= hi: mid = lo + (hi - lo) // 2 # avoids overflow in Java/C++ if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 # mid is ruled out: skip it else: hi = mid - 1
# "First true" version: smallest index where ok(i) is truelo, hi = 0, n # hi = n means "none found"while lo < hi: mid = lo + (hi - lo) // 2 if ok(mid): hi = mid # mid might be the answer: keep it else: lo = mid + 1return loPick one invariant and stick to it. Inclusive [lo, hi] pairs with while lo <= hi
and mid +/- 1. Half-open [lo, hi) pairs with while lo < hi and hi = mid. Mixing
the two causes infinite loops (lo = mid with a lower mid) or skipped answers.
Binary search on the answer
Section titled “Binary search on the answer”Sometimes there is no array to search. Instead, guess a value x, test “does x
work?” in O(n), and binary search over the range of possible x. If bigger x never
makes a working guess stop working, the test is monotonic. Koko Eating Bananas (875) is
the classic: search eating speeds from 1 to the largest pile. Cost: O(n log range).
Problems in this guide
Section titled “Problems in this guide”- Binary Search — the plain template on a sorted array
- Search in Rotated Sorted Array — one half is always sorted; check which