The problem, in one line. Piles of bananas must all be eaten within h hours, one pile at a time, at a steady speed per hour. Return the slowest speed that still finishes in time. LeetCode 875.
The tell. “The minimum X such that”, and a faster X never hurts. That makes every speed either too slow or fast enough, with one boundary between them, and the boundary is what you search for.
The wrong first idea
Divide the total bananas by the hours and use that as the speed.
total = sum(piles)
return -(-total // h) # ceiling of total / h
Too small. A pile is eaten in whole hours, so a pile of 9 at speed 4 costs 3 hours, not 2.25. The leftover time inside each hour is wasted, so the real answer is often higher.
The invariant
The clinic builds this from scratch: Clinic #33: Koko Eating Bananas. Test a speed by adding up the hours each pile needs, rounding each up.
flowchart LR A["piles 4 9 12 2, h = 6<br/>lo 1, hi 12<br/>mid 6: 1+2+2+1 = 6 hours<br/>fits, hi = 6"] --> B["lo 1, hi 6<br/>mid 3: 2+3+4+1 = 10<br/>too slow, lo = 4"] B --> C["lo 4, hi 6<br/>mid 5: 1+2+3+1 = 7<br/>too slow, lo = 6"] C --> D["lo = hi = 6<br/>answer 6"]
The sentence that stays true every step: every speed below lo is too slow, and the speed at hi is fast enough. On a yes, keep the middle. On a no, drop it.
The solution
def min_eating_speed(piles, h):
lo, hi = 1, max(piles) # the answer lives in [1, biggest pile]
while lo < hi:
mid = (lo + hi) // 2
hours = sum((p + mid - 1) // mid for p in piles) # round each pile up
if hours <= h:
hi = mid # fast enough: the answer is mid or slower
else:
lo = mid + 1 # too slow: the answer is faster
return lo
print(min_eating_speed([4, 9, 12, 2], 6))
print(min_eating_speed([4, 9, 12, 2], 4))
print(min_eating_speed([10], 5))
6
12
2
func minEatingSpeed(piles []int, h int) int {
lo, hi := 1, 0
for _, p := range piles {
hi = max(hi, p) // the answer lives in [1, biggest pile]
}
for lo < hi {
mid := (lo + hi) / 2
hours := 0
for _, p := range piles {
hours += (p + mid - 1) / mid // round each pile up
}
if hours <= h {
hi = mid // fast enough: the answer is mid or slower
} else {
lo = mid + 1 // too slow: the answer is faster
}
}
return lo
}
Same three calls print 6, 12, 2.
Complexity
- Time O(n log m): each test reads all n piles, and the search tries about log of the biggest pile m speeds.
- Space O(1): no extra structure.
Traps
- Counting hours with plain division,
p // mid. A pile of 9 at speed 4 becomes 2 hours instead of 3, so slow speeds look fast enough. - Writing
lo = midon a no. Withlo = 3andhi = 4the middle is 3 again, the range never shrinks, and the loop hangs. - Starting
loat 0. The first middle can be 0, and the hours formula divides by it.
Next in the ladder
Minimum Time to Complete Trips has the same shape with the roles flipped: you search for a time, and testing it means adding up the trips each bus finishes.