Problem 17 · Binary Search
Koko Eating Bananas
01Problem
Given pile sizes and h hours, find the minimum integer eating speed k so all piles are finished within h hours (one pile per hour max).
02Key insight
Binary search on the answer: feasibility (hours needed at speed k) is monotonic in k, so find the smallest feasible k in [1, max(piles)].
03Solution
Try it first.
TimeO(n log max(piles))
SpaceO(1)
tests.py · 4 passing
tests.pypython4 lines
assert min_eating_speed([3,6,7,11], 8) == 4
assert min_eating_speed([30,11,23,4,20], 5) == 30
assert min_eating_speed([30,11,23,4,20], 6) == 23
assert min_eating_speed([1], 1) == 104Staff-level follow-up
Where does this pattern show up in real systems? Capacity planning: minimum workers/throughput to meet an SLA, or minimum shard size to fit partitions into N nodes, whenever feasibility is monotonic.