Koko Eating Bananas
Difficulty: Medium
Koko has several piles of bananas and h hours before the guards return. She picks one eating speed k (bananas per hour) and keeps it all day.
Each hour, she eats up to k bananas from one pile. If the pile has fewer than k left, she finishes it and waits until the next hour to start another pile.
Find the smallest whole-number speed k that lets her finish every pile within h hours.
Examples
Input: piles = [3, 6, 7, 11], h = 8
Output: 4
At speed 4, the hours needed are ceil(3/4) + ceil(6/4) + ceil(7/4) + ceil(11/4) = 1 + 2 + 2 + 3 = 8, which just fits. Any slower speed would take more than 8 hours.
Input: piles = [30, 11, 23, 4, 20], h = 5
Output: 30
With only 5 hours for 5 piles, Koko gets exactly one hour per pile, so she must be fast enough to clear the biggest pile, 30, in a single hour.
Input: piles = [30, 11, 23, 4, 20], h = 6
Output: 23
At speed 23 the hours needed add up to exactly 6; speed 22 would need 7 hours, which is too slow.
Constraints
1 <= piles.length <= 10^4
piles.length <= h <= 10^9
1 <= piles[i] <= 10^9
Approach
The direct way tries every speed from 1 and stops at the first one that finishes in time. It's correct, but there can be as many speeds as the biggest pile, which is slow.
The key point: eating faster never takes longer. So every speed is either "too slow" (more than h hours) or "fast enough" (at most h hours), and all the "too slow" speeds come first.
When a yes/no question has a clean boundary like this, you can binary search over the possible answers (here, speeds) instead of an array, to find the smallest speed that's "fast enough."
Solutions
Brute Force — Try Every Speed
Starting at speed 1, check the hours needed and stop at the first speed that fits within h hours.
function minEatingSpeed(piles, h) {
const hoursNeeded = (speed) => {
let hours = 0;
for (const pile of piles) {
hours += Math.ceil(pile / speed);
}
return hours;
};
let speed = 1;
while (hoursNeeded(speed) > h) {
speed++;
}
return speed;
}Time: O(n * max(piles)) · Space: O(1)
Optimal — Binary Search on the Answer
Binary search over speeds from 1 to the largest pile. If a speed fits within h hours, try slower; otherwise try faster.
function minEatingSpeed(piles, h) {
const hoursNeeded = (speed) => {
let hours = 0;
for (const pile of piles) {
hours += Math.ceil(pile / speed);
}
return hours;
};
let low = 1;
let high = Math.max(...piles);
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (hoursNeeded(mid) <= h) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
}Time: O(n * log(max(piles))) · Space: O(1)