codebrew.ai

Koko Eating Bananas

Binary search the answer: eating speed is monotonic in whether she finishes in time.

Approach

The feasible speeds form a monotonic predicate — any speed fast enough works, slower ones don't. Binary search speeds between 1 and max(pile); for each candidate, sum the hours needed and check against h. Return the smallest feasible speed.

Time complexity

O(n log max)

Space complexity

O(1)

Common mistake

Searching values in the array instead of the answer space [1, max pile] — this is 'binary search on the answer'.

See it run, step by step

Generate an interactive lesson for Koko Eating Bananas — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Koko Eating Bananas

Related problems