Koko Eating Bananas
WHAT IT SAYS
Find the minimum eating speed to finish all piles in h hours.
WHAT IT'S REALLY ASKING
"The answers form a line of no, no, no, yes, yes, yes — can you see the array hiding in that?"
Brute force: try every speed
O(max(pile) · n) timeTest k = 1, 2, 3, … until one finishes in time. Each test simulates all the piles.
WHERE THE WORK IS WASTED — If speed k succeeds, every speed above k succeeds too. You're walking a sorted sequence of yes/no answers one at a time — the exact situation linear search exists to be replaced in.
Feasibility is monotonic, so the answer space is searchable.
"Can Koko finish at speed k?" flips from false to true exactly once and never flips back. Any monotone yes/no sequence can be binary searched — even when it isn't an array in memory, just a range of candidate answers. The array was imaginary all along; binary search never cared.
Binary search the answer space
O(n · log max(pile)) timeSearch k in [1, max(pile)]. Midpoint feasible → the boundary is at mid or left of it. Infeasible → it's right of mid. The feasibility check is a cheap O(n) simulation.
Binary Search on the Answer
YOU'LL SEE IT AGAIN WHEN
- "Minimum speed / capacity / days such that…"
- A cheap check(x) that is monotone in x
- The answer lives in a numeric range, not at an index