Animation10 min

Binary Search on the Answer

'Minimum speed so everything finishes' — guess an answer, check feasibility, halve the range.

Here binary search runs on something that is not an array: the range of possible answers.

The vertical slider is the candidate range for an eating speed (as in Koko Eating Bananas: find the minimum bananas-per-hour so all piles are finished in time). Each step, the handle jumps to the middle of the live range and a mini simulation plays out: at this speed, how many hours do the piles take? It ends in a green check (fast enough) or a red X (too slow).

The key structure to watch: the results are monotone. Every speed below some threshold fails, every speed at or above it works — the track is solid red at the bottom, solid green at the top, with a single boundary between them. That false→true shape is exactly what binary search needs; without it, discarding half the range would be unsafe.

So each simulation kills half the slider: a red X means the whole lower half is red too (discard it), a green check means everything above mid is also green (discard it, but keep mid as the best answer so far). Watch the handle home in on the lowest green mark — the minimum feasible speed — using only about log(range) simulations instead of testing every speed.