← Back to DSA Animator
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 Answer Space  
1 ?
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.