The idea is bigger than sorted arrays. Binary search works on any yes/no question that flips once: false, false, false, then true, true. Find the first true, and you can answer "first index not less than x", "smallest speed that finishes in time" or "peak of a mountain array" with the same loop.
When to use it
- The input is sorted, or sorted in pieces (rotated, a matrix with sorted rows and columns).
- You need the first or last position of something, not just whether it exists.
- The question asks for the smallest or largest value that works, and checking one value is easy (search on the answer).
- n is large (10^5 and up) and the expected solution is O(log n) or O(n log n).
The template
def first_true(lo, hi, ok): # ok() flips once: False...False True...True
while lo < hi:
mid = (lo + hi) // 2 # lower middle, so hi = mid always shrinks
if ok(mid):
hi = mid # mid works: the answer is mid or earlier
else:
lo = mid + 1 # mid fails: the answer is after it
return lo # first value where ok() is True
# lower bound: first index i with nums[i] >= x
# first_true(0, len(nums), lambda i: nums[i] >= x)The variants you will meet
Exact match
The textbook version: keep [lo, hi], compare the middle with the target, return when equal. It only works when the data is sorted by the thing you compare.
Lower and upper bounds
The first index not less than x, and the first index greater than x. Together they give the range of x and its count, and they are what bisect_left and bisect_right return.
Search on the answer
When the answer is a number and "does x work?" flips once as x grows, binary search the answer itself: Koko eating bananas, shipping within D days, splitting an array to minimise the largest sum.
Rotated, unbounded and peaks
A rotated sorted array still has one sorted half at every middle, so you can tell which half to keep. Unknown lengths are handled by doubling until you overshoot; peaks by following the rising side.
Matrices
A matrix whose rows continue each other is one sorted list of m·n items. A matrix sorted by rows and by columns is better searched from a corner, one row or column per step.
Real numbers
For square roots and other real answers, loop a fixed number of times or until the range is smaller than the precision you need, and prefer integer searches when the answer is an integer.
Time and space complexity
O(log n) comparisons, because each step halves the range: 2^20 is about a million, so 20 steps cover it. Search on the answer costs O(log R) checks over a range of size R, times the cost of one check. Extra space is O(1) for the loop.