DSA AnimatorDSA animations
Koko Eating Bananas LC #875 Medium Binary Search on Answer
Problem

Koko loves to eat bananas. There are n piles of bananas; the i-th pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her eating speed k bananas/hour. Each hour she picks one pile and eats up to k bananas from it. She may eat less than k if the pile has fewer. Return the minimum integer k such that she can eat all the bananas within h hours.

Example 1
Input: piles = [3,6,7,11], h = 8
Output: 4
Explanation: Speed 4 → ⌈3/4⌉+⌈6/4⌉+⌈7/4⌉+⌈11/4⌉ = 1+2+2+3 = 8 hours.
Example 2
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Explanation: h = n = 5, must finish each pile in exactly 1 hour.
Example 3
Input: piles = [1,1,1,1], h = 4
Output: 1
Explanation: Speed 1 finishes each pile in 1 hour, total 4 hours.
Constraints: 1 ≤ piles.length ≤ 10⁴  |  piles.length ≤ h ≤ 10⁹  |  1 ≤ piles[i] ≤ 10⁹
Try Examples
Custom:
Speed & Time Gauges
eating speed k
—
answer space [1, max(piles)]
hours used
💂
—
guard returns at ?h
Banana Piles   🐵
State Variables
lo
—
hi
—
mid = k
—
total hours
—
h limit
—
feasible?
—
Step Logic
Select an example above and press Play to begin.
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init lo=1, hi=max(piles) — the answer space for speed k
2
Compute mid = lo + (hi-lo)/2 and evaluate hours = Σ⌈pile/mid⌉
3
If hours ≤ h: mid is feasible — try slower: hi = mid
4
If hours > h: too slow — need faster: lo = mid + 1
5
When lo == hi: found minimum feasible speed — return lo
Time
O(n log M)
Space
O(1)
Why Binary Search Works

The feasibility function is monotone: if eating speed k lets Koko finish in ≤ h hours, then any speed k' > k is also feasible (faster = fewer hours). So we binary search for the leftmost feasible speed. Each check costs O(n), and the answer space is [1, max(piles)], giving O(n log(max)) overall.

How to solve Koko Eating Bananas

LeetCode 875 · Medium · Binary Search · Pattern: Binary Search on Answer

Why the obvious approach is slow

Trying every speed from 1 to the biggest pile is O(n) times max. But if a speed works, every faster speed also works.

The key idea

That makes the answer space sorted: too slow, then fast enough. Binary search the speed between 1 and the largest pile. For each guess, the hours needed is the sum of each pile divided by k, rounded up.

Remember

When a yes stays yes as the value grows, binary search the answer. The check function decides which half to keep.

Run the animation above on your own input, or watch the 1:20 video explanation of Koko Eating Bananas with a dry run and Java code.

More Binary Search problems