Koko Eating Bananas Solution
Find the minimum eating speed k such that Koko can eat all bananas within h hours.
Problem Statement
There are n piles of bananas with piles[i] bananas each. Guards return in h hours. Koko eats at speed k bananas/hour. Each hour she picks a pile and eats k bananas (if fewer remain, she eats them all and waits). Find the minimum integer k such that she can eat all bananas within h hours.
Brute Force — O(n · max)
Try every speed from 1 upward. For each speed, compute total hours needed. Return the first speed that works.
| Metric | Value |
|---|---|
| Time | O(n · max(piles)) |
| Space | O(1) |
Binary Search on Answer — O(n log max)
Binary search the speed k in range [1, max(piles)]. For each candidate speed, compute total hours = Σ ceil(piles[i] / k). If total ≤ h, try a smaller speed (go left). Otherwise, try a larger speed (go right).
- Step 1:
left = 1,right = max(piles). - Step 2: Compute
mid = (left + right) / 2. - Step 3: Compute total hours at speed mid:
Σ ceil(piles[i] / mid). - Step 4: If total ≤ h → speed might be too high (or just right), try lower:
right = mid. - Step 5: If total > h → speed too slow:
left = mid + 1. - Step 6: Return
left.
- When the problem asks for the minimum/maximum value that satisfies a condition, and you can write a feasibility check function, binary search the answer space.
- The check must be monotonic: if speed k works, all k' > k also work.
- This pattern appears in LC 875, LC 1011 (Ship Within D Days), LC 410 (Split Array Largest Sum), and LC 774 (Minimize Max Distance to Gas Station).
ceil(a / b) = (a + b - 1) / busing integer arithmetic. Avoids floating-point precision issues.- In Python you can also use
-(-a // b).
Visual Walkthrough
Trace through piles = [3, 6, 7, 11], h = 8:
Code — Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Brute Force | O(n · max) | O(1) | Try every speed linearly |
| Binary Search on Answer ← optimal | O(n · log(max)) | O(1) | log(max) candidates × O(n) feasibility check |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| h == n | [3,6,7,11], h=4 | Exactly one hour per pile → k = max(piles) = 11. |
| h very large | [3,6,7,11], h=10⁹ | k=1 works — plenty of time. Binary search converges to 1. |
| Single pile | [30], h=5 | Need ceil(30/k) ≤ 5 → k ≥ 6. |
| All piles size 1 | [1,1,1], h=3 | k=1 → 3 hours exactly. Minimum speed. |
| Integer overflow | Large piles, small k | Sum of hours can exceed int range. Use long in Java. |
left ≤ right instead of left < right. This is a "find minimum feasible" search — the answer converges when L==R. With ≤ and right = mid, the loop never terminates when L==R.