loading

Koko Eating Bananas — Step-by-Step Visualization

mediumLeetCode #875ArrayBinary Search

Koko loves to eat bananas. There are `n` piles of bananas, the `i`-th pile has `piles[i]` bananas. Koko can decide her bananas-per-hour eating speed `k`. Each hour, she eats `k` bananas from a single pile. She must finish all piles within `h` hours. Return the minimum integer `k` such that she can eat all the bananas within `h` hours.

Algorithm Pattern

Binary Search on Answer

Key Idea

Binary search on the eating speed k from 1 to max(piles). For each k, check if she can finish all piles in h hours.

Step-by-Step Approach

  1. lo = 1, hi = max(piles).
  2. mid = (lo + hi) // 2.
  3. hours = sum(ceil(pile / mid) for pile in piles).
  4. If hours <= h: valid speed, try smaller → res = mid, hi = mid - 1.
  5. Else too slow → lo = mid + 1.
  6. Return res.

Common Gotchas

  • Use ceil division: ceil(p / k) = (p + k - 1) // k.
  • The answer space is 1..max(piles), not 1..sum(piles).

Related Problems