mediumBinary SearchBinary Search

Koko Eating Bananas

mediumTime: O(n log m)Space: O(1)

Recognize the pattern

minimize maximum eating speedcan finish in h hours?binary search on the answer

Brute force idea

The naive version of Koko Eating Bananas sounds like this: Try every speed from 1 to max(piles) and simulate. Tests every possible speed linearly. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The real unlock in Koko Eating Bananas comes when you notice this: Binary search on the speed: for each candidate speed, check if Koko can finish all piles in h hours. The check is, and binary search reduces candidates from max to log(max). Total. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Koko Eating Bananas is this: If Koko can finish at speed k, she can finish at any speed > k. If she can't finish at speed k, she can't at any speed < k. This monotonicity makes binary search valid. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in Koko Eating Bananas is this: The ceiling division: hours for one pile = ceil(pile / speed), not floor. Forgetting ceiling means underestimating the time. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Binary Search Pattern