Learn / Binary search

Binary search on the answer

Sometimes there is no sorted array to search, but the answer itself is a number in a known range, and you can check any guess quickly. If every guess above the answer passes and every guess below fails (or the other way round), binary search the guesses instead of the data.

How to recognise it

  • The question says "minimum speed", "smallest capacity", "least days", "maximum distance", "minimise the largest" or "maximise the smallest".
  • Checking one guess is easy (often one greedy pass), but finding the best value directly is hard.
  • Making the guess bigger only ever makes the check easier (or only ever harder). That is the monotonic property.
  • The answer lies in a range you can write down, such as 1 to the largest value, or the largest value to the total sum.

The idea in one picture

Imagine a row of light switches labelled 1, 2, 3 and so on, one for every possible answer. Each switch is off if that guess fails the check and on if it passes. If the row looks like off, off, off, on, on, on, the best answer is the first switch that is on, and binary search finds it in log₂(range) checks. No sorted array is needed, only that row of switches with one change.

Two shapes: smallest that works, largest that works

ShapeTypical wordsRow of guessesTemplate
Smallest guess that passesminimum speed, least days, smallest divisorfail … fail pass … passif pass(mid): hi = mid else lo = mid + 1
Largest guess that passesmaximum distance, highest bladepass … pass fail … failif pass(mid): lo = mid else hi = mid - 1, with mid rounded up

"Minimise the largest" problems (Split Array, Painter's Partition) are the first shape: guess a limit, and check whether the work can be split into at most k parts that each stay under it.

Template

lo = smallest possible answer, hi = largest possible answer
while lo < hi:
    mid = lo + (hi - lo) / 2
    if check(mid): hi = mid        # mid works, maybe something smaller does too
    else: lo = mid + 1             # mid fails, so everything below it fails too
return lo

The real work is writing check. It is usually one greedy pass over the input:

ProblemGuessCheck
Koko Eating Bananasspeed ktotal hours Σ ceil(pile / k) ≤ h
Minimum days for bouquetsday denough runs of k bloomed flowers
Aggressive Cowsdistance dgreedy places at least k cows
Split Array, Painter's Partitionlimit Lgreedy needs at most k parts
EKOblade height Hwood cut Σ max(0, h - H) ≥ m

Common mistakes

  • Choosing a range that does not contain the answer, such as starting at 0 for a speed, which divides by zero.
  • Rounding mid down in the "largest that passes" template, which loops forever when two guesses are left.
  • Overflowing in check: sums of hours, wood or products often need 64-bit numbers.
  • Binary searching when the check is not monotonic. Test a few guesses by hand first.

Problems

0 of 15 solved

Check yourself

In Koko Eating Bananas, why can you binary search on the speed k?

For Split Array Largest Sum, what is the smallest possible answer, and the largest?

You want the largest guess that passes, using lo = mid when it passes and hi = mid - 1 when it fails. How must mid be computed?

In Aggressive Cows, why place cows greedily from the left when checking a distance d?

When the answer is a real number, as in Minimize Max Distance to Gas Station, how do you stop?