Koko Eating Bananas
Use binary search on the answer to find the minimum valid eating speed.
Try It Yourself
Use the editor below to search possible eating speeds rather than array positions. For each candidate speed, calculate how many whole hours all piles require.
Submit your implementation when it passes the examples. The answer may be one, the largest pile, or a speed between them.
Koko Eating Bananas
Koko has several piles of bananas and h hours. At an integer speed k, she spends one hour consuming up to k bananas from one pile.
Return the smallest speed that lets her finish every pile within h hours.
Example 1:
Example 2:
Constraints
1 ≤ piles.length ≤ h ≤ 100,0001 ≤ piles[i] ≤ 1,000,000,000
Solution
Possible speeds form an ordered range from 1 through the largest pile. A candidate is feasible when the sum of each pile's rounded-up division by that speed is no more than h.
If a speed is feasible, keep it as a possible answer and search lower speeds. Otherwise, discard it and every slower speed.
function minEatingSpeed(piles, h) {
let left = 1;
let right = Math.max(...piles);
while (left < right) {
const speed = left + Math.floor((right - left) / 2);
let hours = 0;
for (const pile of piles) {
hours += Math.ceil(pile / speed);
}
if (hours <= h) right = speed;
else left = speed + 1;
}
return left;
}Big O notation
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n log m) | Each of log m candidate speeds scans all n piles, where m is the largest pile. |
| Auxiliary space | O(1) | Only search boundaries and the current hour total are stored. |