Algorithms Playbook
PatternTime O(n log M) · Space O(1)9 min read

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.

Binary search on the answer: the slowest speed that still finishes in time
Example
Speed
0112233445566778899101011lohipiles = [3, 6, 7, 11] · h = 8
1def min_speed(piles, h):
2 lo, hi = 1, max(piles)
3 while lo < hi:
4 speed = (lo + hi) // 2
5 hours = sum(ceil(p / speed) for p in piles)
6 if hours <= h:
7 hi = speed # fast enough: try slower
8 else:
9 lo = speed + 1 # too slow: go faster
10 return lo
There's no array to search, so search the answers: speeds from 1 to 11 (eating the biggest pile in one hour is always enough).

Variables

lo1
hi11
speed—
hours—
h8
Step 1/10· Checks: 0
The check "can I finish at this speed?" is monotonic: once it's yes, every faster speed is yes too. That's all binary search needs.

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 < hi and hi = mid: we keep mid because it may be the answer. The loop ends when lo == hi.
  • Choose lo and hi so the answer is surely inside: e.g. speed between 1 and the biggest pile.
  • For "maximum value that works", flip it: lo = mid when it works and use mid = (lo + hi + 1) // 2 to avoid an infinite loop.

Problems with the same shape

ProblemSearch overworks(x)
Koko eating bananasSpeedTotal hours ≤ h
Ship packages within D daysShip capacityDays needed ≤ D
Split array largest sumMax allowed sumPieces needed ≤ m
Minimum days to make bouquetsDayBouquets ready ≥ m
Integer square rootCandidate rootx² ≤ 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