Koko Eating Bananas
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Koko eats k bananas per hour from one pile per hour. Find the smallest k that finishes all piles within h hours.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1If speed k works, does a faster speed also work?
- Hint 2For a given speed, how many hours does one pile of p bananas take?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
You must finish several chapters before an exam in 8 hours, studying one chapter at a time (you cannot mix chapters within an hour). What is the slowest pace in pages per hour that still finishes in time? Try a pace: too slow to finish in 8 hours? Go faster. Finishes with time to spare? Try slower. Bisect the pace, not the chapters.
- The obvious way
Try speeds 1, 2, 3, ... and simulate each: too slow when piles are huge.
- The key insight
A pile of p bananas needs ceil(p / speed) hours, so the total hours only go down as speed rises. The speeds that work form a range from the answer up to the biggest pile. Binary search the speed between 1 and the biggest pile, checking each guess in one pass over the piles.
- The algorithm
- Speed range: 1 up to the biggest pile.
- Guess the middle speed; total hours = sum over piles of ceil(pile / speed).
- Within the allowed hours? It works: try slower (keep this speed as a candidate).
- Too many hours? Too slow: try faster. Stop when the range is one speed.
Watch it run
Examplepiles = [3, 6, 7, 11], hours = 8
Guess speed 6: piles take 1 + 1 + 2 + 2 = 6 hours. That is within 8, so try slower.
speed range 1 to 6
Where people slip
- Use integer ceiling (pile + speed - 1) / speed, not float division.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def min_eating_speed(piles, hours):
slowest, fastest = 1, max(piles)
while slowest < fastest:
speed = (slowest + fastest) // 2
needed = sum((pile + speed - 1) // speed for pile in piles) # ceil(pile / speed)
if needed <= hours:
fastest = speed # this speed works: try slower
else:
slowest = speed + 1 # too slow: speed up
return slowestNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.