Binary search on the answer: when there's no array to search
Many "find the minimum (or maximum) value such that…" problems hide a binary search over the possible answers. How to spot it, the yes/no check, and the template.
In short
If you can write a check `works(x)` that is false, false, … then true, true, … as x grows, binary search over x for the first true. Cost: O(log of the range × cost of one check).
The idea: guess, check, halve
Koko has piles of bananas and h hours. At speed k she eats up to k bananas from one pile per hour. What's the slowest speed that finishes in time? You could try speed 1, 2, 3… but notice: if speed 6 works, 7 works too. The answers are monotonic.
So binary search the speed. Each guess costs one pass over the piles to count the hours, and halves the range of speeds.
1def min_speed(piles, h):2 lo, hi = 1, max(piles)3 while lo < hi:4 speed = (lo + hi) // 25 hours = sum(ceil(p / speed) for p in piles)6 if hours <= h:7 hi = speed # fast enough: try slower8 else:9 lo = speed + 1 # too slow: go faster10 return lo
Variables
The template (first value that works)
lo, hi = smallest_possible, largest_possible
while lo < hi:
mid = (lo + hi) // 2
if works(mid):
hi = mid # mid might be the answer: keep it
else:
lo = mid + 1 # mid is too small: discard it
return lo- Here it's
lo < hiandhi = mid: we keepmidbecause it may be the answer. The loop ends whenlo == hi. - Choose
loandhiso the answer is surely inside: e.g. speed between 1 and the biggest pile. - For "maximum value that works", flip it:
lo = midwhen it works and usemid = (lo + hi + 1) // 2to avoid an infinite loop.
Problems with the same shape
| Problem | Search over | works(x) |
|---|---|---|
| Koko eating bananas | Speed | Total hours ≤ h |
| Ship packages within D days | Ship capacity | Days needed ≤ D |
| Split array largest sum | Max allowed sum | Pieces needed ≤ m |
| Minimum days to make bouquets | Day | Bouquets ready ≥ m |
| Integer square root | Candidate root | x² ≤ n |
Key takeaways
- 01If works(x) flips from false to true once, binary search over x.
- 02Bound the answer with lo and hi, then halve with a yes/no check.
- 03Use lo < hi and hi = mid to find the first value that works.
- 04Cost: O(log range) checks, each usually O(n).
Check your understanding
1 of 3
What property must the check works(x) have?
Related topics