Koko Eating Bananas – Solution & Complexity
Solution Walkthrough
Step 1: Recognize a monotonic predicate
- Define
feasible(k)= "Koko finishes withinhhours at speedk". - If a speed works, every larger speed also works, and if a speed fails, every smaller speed also fails.
- That monotonic yes/no boundary is the hallmark of binary-searching the answer rather than a sorted array.
- Define
Step 2: Compute hours at a given speed
- At speed
k, a pile ofpbananas takesceil(p / k)hours because only one pile is eaten per hour. - Sum
ceil(p / k)over all piles; the speed is feasible when that total is<= h. - Use integer math:
ceil(p / k)is(p + k - 1) / kwith integer division.
- At speed
Step 3: Bound the search
- The slowest sensible speed is
1banana per hour. - The fastest useful speed is
max(piles): going faster never reduces the hour count below one pile per hour. - So the answer lies in
[1, max(piles)].
- The slowest sensible speed is
Step 4: Brute-force baseline
- Try speeds
1, 2, 3, ...and stop at the first feasible one. - Correct but up to
O(max(piles) * n)time — fine as a reference, too slow for the largest inputs.
- Try speeds
Step 5: Binary search the speed
- Search the boundary in
[1, max(piles)]. - When
midis feasible, it might still be too fast, so keep it and movehidown tomid. - When
midis infeasible, discard it and everything slower by settinglo = mid + 1. - The loop converges on the smallest feasible speed.
- Search the boundary in
Step 6: Common mistakes
- Using floating-point division and
roundinstead of a true ceiling — off-by-one hours creep in. - Setting
hi = mid - 1whenmidis feasible, which can skip the real answer. - Starting
hiabovemax(piles), which still works but wastes iterations.
- Using floating-point division and