Koko Eating Bananas
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Binary Search.
Koko Eating Bananas
Koko loves to eat bananas. There are
n piles of bananas, the i-th pile has piles[i] bananas. The guards will come back in h hours. Koko can decide her bananas-per-hour eating speed k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Return the minimum integer k such that she can eat all the bananas within h hours.Examples
Input: piles = [3,6,7,11], h = 8
Output: 4
Approach 1
Level I: Brute Force
Intuition
Try every speed
k starting from 1 upwards until we find one that allows Koko to finish in h hours.⏱ $O(Max(Piles) \cdot N)$💾 $O(1)$
Detailed Dry Run
piles=[3,6,7,11], h=8. Try k=1, 2, 3... until 4 fits.
Approach 2
Level III: Optimal (Binary Search on Answer)
Intuition
The time spent eating is a monotonic function of the speed
k. We can binary search in the range [1, max(piles)].⏱ $O(N \cdot \log(Max))$💾 $O(1)$
Detailed Dry Run
piles=[3,6,7,11], h=8. L=1, R=11.
- Mid 6: 1+1+2+2 = 6 <= 8. R=6.
- Mid 3: 1+2+3+4 = 10 > 8. L=4.
- Mid 5: 1+2+2+3 = 8 <= 8. R=5.
- Mid 4: 1+2+2+3 = 8 <= 8. R=4. Result 4.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.