TRT
Sign in
mediumCoreLeetCode#binary search on the answer

Koko eating bananas

Find the slowest eating speed that finishes all piles within h hours, by binary searching over speeds with a feasibility check.

The Runtime Theory Team1 min read
Taught inSearching an answer spacePro — members onlyWhen a yes-or-no check about a candidate answer flips exactly once, from no to yes, you can binary search over the answers themselves, even when no array exists.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inpiles = [3, 6, 7, 11], h = 8

out4

inpiles = [30, 11, 23, 4, 20], h = 5

out30

inpiles = [30, 11, 23, 4, 20], h = 6

out23

Koko eats bananas from piles at k bananas per hour; each hour she eats from one pile, and if it has fewer than k bananas she finishes it and waits for the next hour. Return the minimum k that lets her finish all piles within h hours.

Before you code

There is no array to search, but there is a range of speeds, from 1 to the largest pile, and a check that flips once: too slow, too slow, …, fast enough, fast enough.

Hints

  1. hours(k) = sum(ceil(p / k)), computed as (p + k - 1) // k to stay in integers.
  2. Search [1, max(piles)] for the first k with hours(k) <= h.
  3. Cost: O(n log M) for n piles of size up to M.

Production & complexity notes

When solving Koko eating bananas on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Searching an answer space to reinforce the underlying pattern.

What it practices

Binary search on the answer, from Searching an answer space.

Not started

Sign in to save your learning progress.

Sign in to save