Koko Eating Bananas - Problem

Koko the gorilla loves bananas! ๐ŸŒ There are n piles of bananas scattered around, where the i-th pile contains piles[i] bananas. The guards have left and will return in exactly h hours.

Koko must decide on her eating speed k (bananas per hour). Each hour, she picks one pile and eats at most k bananas from it. If a pile has fewer than k bananas, she eats the entire pile and then takes a break for the rest of that hour.

Koko wants to eat slowly (she's a mindful eater!), but she also needs to finish all the bananas before the guards return. Your task is to find the minimum eating speed k that allows her to consume all bananas within h hours.

Input & Output

example_1.py โ€” Basic Case
$ Input: piles = [3,6,7,11], h = 8
โ€บ Output: 4
๐Ÿ’ก Note: At speed 4: pile 3 takes 1h, pile 6 takes 2h, pile 7 takes 2h, pile 11 takes 3h. Total = 8h exactly.
example_2.py โ€” More Time Available
$ Input: piles = [30,11,23,4,20], h = 5
โ€บ Output: 30
๐Ÿ’ก Note: With only 5 hours for 5 piles, Koko must eat the largest pile (30) in 1 hour, so minimum speed is 30.
example_3.py โ€” Plenty of Time
$ Input: piles = [30,11,23,4,20], h = 6
โ€บ Output: 23
๐Ÿ’ก Note: At speed 23: piles take [2,1,1,1,1] hours respectively, totaling 6 hours exactly.

Constraints

  • 1 โ‰ค piles.length โ‰ค 104
  • piles.length โ‰ค h โ‰ค 109
  • 1 โ‰ค piles[i] โ‰ค 109
  • Key constraint: h โ‰ฅ piles.length (enough time to eat at least one pile per hour)

Visualization

Tap to expand
๐ŸŒ Koko's Banana Eating Strategy3bananas6bananas7bananas11bananasโฐ Guards return in 8 hoursBinary Search ProcessSearch eating speed from 1 to 11 bananas/hourFind minimum speed that allows finishing in โ‰ค 8 hoursSpeed = 4Pile 3: โŒˆ3/4โŒ‰ = 1hPile 6: โŒˆ6/4โŒ‰ = 2hPile 7: โŒˆ7/4โŒ‰ = 2hPile 11: โŒˆ11/4โŒ‰ = 3hTotal Time8hoursโ‰ค 8 โœ“Speed = 3Pile 3: โŒˆ3/3โŒ‰ = 1hPile 6: โŒˆ6/3โŒ‰ = 2hPile 7: โŒˆ7/3โŒ‰ = 3hPile 11: โŒˆ11/3โŒ‰ = 4h10h > 8 โœ—๐ŸŽฏ Answer: Minimum speed = 4 bananas/hour
Understanding the Visualization
1
Define Search Space
Reading speed must be between 1 and the thickest book's pages
2
Test Middle Speed
For each book, calculate ceil(pages/speed) hours needed
3
Check Feasibility
If total time โ‰ค h, try slower speed; otherwise need faster speed
4
Narrow Search
Binary search eliminates half the possibilities each iteration
5
Find Minimum
Converge to the slowest speed that still meets the deadline
Key Takeaway
๐ŸŽฏ Key Insight: The problem has a monotonic property - if eating speed k works, then any speed > k also works. This allows us to binary search the answer space efficiently, reducing time complexity from O(max(piles) ร— n) to O(log(max(piles)) ร— n).
Asked in
Amazon 45 Google 35 Meta 28 Microsoft 22
67.2K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen