15% off all plans & roadmaps Use code
See plansKoko Eating Bananas
- LeetCode 875
- Medium
- Binary Search Patterns
- On Answer / Condition Function
Updated
TL;DR: Find the smallest eating speed k so that the total hours across all piles is at most h. Total hours only fall as k rises, so binary search over k finds the answer in O(n log max(piles)).
Problem
Koko loves bananas. There are n piles, and pile i holds piles[i] bananas. The guards are away and will return in h hours.
Koko picks an eating speed of k bananas per hour. Each hour she chooses one pile and eats k bananas from it. If the pile has fewer than k bananas, she finishes that pile and eats nothing else during that hour.
Koko wants to eat as slowly as possible while still finishing every banana before the guards return. Return the minimum integer k that lets her eat all the bananas within h hours.
Example 1
Input: piles = [3,6,7,11], h = 8 Output: 4
Example 2
Input: piles = [30,11,23,4,20], h = 5 Output: 30
Example 3
Input: piles = [30,11,23,4,20], h = 6 Output: 23
Constraints
1 <= piles.length <= 10^4piles.length <= h <= 10^91 <= piles[i] <= 10^9
Constraints that matter
piles[i]up to 10^9 means the speed range is up to 10^9 values. Trying every speed one by one is too slow when the pile is large, so you need a logarithmic search over speeds.piles.length <= hguarantees at least one hour per pile. That means speedmax(piles)always works, since every pile then takes exactly one hour. So the answer always exists and is at mostmax(piles).piles.lengthup to 10^4 means one feasibility check costs about 10^4 operations. About 30 checks cost around 3 * 10^5 operations in total.- Total hours at speed 1 can reach 10^4 * 10^9 = 10^13, which overflows a 32-bit integer. Use a 64-bit accumulator in Java, C++ and C#, or stop adding once the total passes
h.
Hints
Hint 1
This is binary search on the answer.
Hint 2
Try every speed from 1 upward.
Solution
Intuition
This is binary search on the answer. You are not searching an array. You are searching the range of possible speeds, from 1 to max(piles), for the smallest one that works.
Picture a row of fence posts where every post left of some gate is locked and every post right of it is open. The posts are speeds, the gate is the smallest working speed, and each probe at mid tells you which side the gate is on.
What points to it is a question of the form "smallest value such that a condition holds". Given a speed k, checking the condition is easy: add up ceil(pile / k) over all piles and compare with h. Finding k directly is hard, but testing a given k is cheap.
The condition is monotonic. If speed k finishes in time, speed k + 1 also finishes in time, because no pile takes more hours at a higher speed. So the speeds form a row of failures followed by a row of successes, and you want the first success.
At each probe you throw away half of the remaining range. If mid works, the answer is mid or something smaller. If mid fails, the answer is larger than mid. Thirty probes cover a range of 10^9.
Worked example
Input: piles = [1000000000], h = 1000000000 Output: 1 Explanation: There is one pile of 10^9 bananas and Koko has 10^9 hours. At speed 1 she needs exactly 10^9 hours, which fits the limit. No speed below 1 is allowed, so 1 is the answer. The case is useful because it is the largest possible pile and the largest possible h at once, so it stresses overflow and loop length.
Approach 1: Brute force
Try every speed from 1 upward. For each speed, add up the hours each pile needs, and return the first speed whose total is at most h.
A pile of size p at speed k takes ceil(p / k) hours, because Koko cannot start a second pile in the same hour. The first speed that passes is the minimum, since you test speeds in increasing order. The speed max(piles) always passes, so the loop always returns.
Steps
- Compute
hi = max(piles), the largest speed worth trying. - For each
kfrom 1 tohi, sethours = 0. - For each pile
p, addceil(p / k)tohours. Use integer math:(p - 1) / k + 1. - If
hours <= h, returnk. - The loop always returns by
k = hi, so no fallback is needed beyond returninghi.
Dry run
On the example piles = [1000000000], h = 1000000000, the loop starts at k = 1.
k = 1: the single pile needs(10^9 - 1) / 1 + 1 = 10^9hours.10^9 <= 10^9is true, so return 1.
This example exits on the first try. The worst case is an input where the answer is large, such as [30,11,23,4,20] with h = 5. There the loop tries speeds 1 through 30 before returning 30, doing a full pass over the piles each time.
Complexity
| Time | O(n * M) |
|---|---|
| Space | O(1) |
Let n be the number of piles and M be max(piles). The outer loop runs at most M times and each pass over the piles costs n steps, so the time is O(n * M). With M up to 10^9 and n up to 10^4 that is far too slow. The code stores only a few counters, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
hi = max(piles)
for k in range(1, hi + 1):
hours = 0
for p in piles:
hours += (p - 1) // k + 1 # ceil(p / k)
if hours <= h:
return k
return hiJavaTested in our runner
import java.util.*;
class Solution {
public int minEatingSpeed(int[] piles, int h) {
int hi = 0;
for (int p : piles) {
hi = Math.max(hi, p);
}
for (int k = 1; k <= hi; k++) {
long hours = 0;
for (int p : piles) {
hours += (p - 1) / k + 1; // ceil(p / k)
}
if (hours <= h) {
return k;
}
}
return hi;
}
}C++Tested in our runner
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int hi = 0;
for (int p : piles) {
hi = max(hi, p);
}
for (int k = 1; k <= hi; k++) {
long long hours = 0;
for (int p : piles) {
hours += (p - 1) / k + 1; // ceil(p / k)
}
if (hours <= h) {
return k;
}
}
return hi;
}
};JavaScriptTested in our runner
/**
* @param {number[]} piles
* @param {number} h
* @return {number}
*/
var minEatingSpeed = function(piles, h) {
let hi = 0;
for (const p of piles) {
hi = Math.max(hi, p);
}
for (let k = 1; k <= hi; k++) {
let hours = 0;
for (const p of piles) {
hours += Math.floor((p - 1) / k) + 1; // ceil(p / k)
}
if (hours <= h) {
return k;
}
}
return hi;
};GoTested in our runner
func minEatingSpeed(piles []int, h int) int {
hi := 0
for _, p := range piles {
if p > hi {
hi = p
}
}
for k := 1; k <= hi; k++ {
hours := 0
for _, p := range piles {
hours += (p-1)/k + 1 // ceil(p / k)
}
if hours <= h {
return k
}
}
return hi
}C#Tested in our runner
public class Solution {
public int minEatingSpeed(int[] piles, int h) {
int hi = 0;
foreach (int p in piles) {
hi = Math.Max(hi, p);
}
for (int k = 1; k <= hi; k++) {
long hours = 0;
foreach (int p in piles) {
hours += (p - 1) / k + 1; // ceil(p / k)
}
if (hours <= h) {
return k;
}
}
return hi;
}
}
Solution pattern
On Answer / Condition Function
Part of Binary Search Patterns
Approach 2: Binary search on speedOptimalOn Answer / Condition Function
What's slow: the brute force re-tests speeds that are too slow or too fast, one at a time, up to 10^9 of them. Each test tells you nothing that the previous test did not already imply.
The insight that fixes it: total hours never increase as speed increases. So one test at speed mid rules out a whole side of the range. If mid finishes in time, every faster speed also does, and the answer is at most mid.
If mid fails, every slower speed also fails, and the answer is above mid. Halving the range each time cuts the number of tests from about 10^9 to about 30.
Use the half-open style loop while lo < hi. When mid works, set hi = mid so the candidate stays in range. When it fails, set lo = mid + 1. The loop ends with lo == hi, and that value is the smallest feasible speed.
Why it is correct. The answer always stays inside the range from lo to hi, because hi is feasible and nothing below lo can be. A feasible mid moves hi down onto mid, which keeps hi feasible. An infeasible mid proves every speed up to mid fails, so lo moves past it.
Steps
- Set
lo = 1andhi = max(piles). Speedhiis always feasible becausepiles.length <= h. - While
lo < hi, computemid = lo + (hi - lo) / 2. - Compute
hoursas the sum of(p - 1) / mid + 1over all piles, using a 64-bit total. - If
hours <= h, thenmidworks and a smaller speed might too, so sethi = mid. - Otherwise
midis too slow, so setlo = mid + 1. - When the loop ends,
lo == hi. Returnlo.
Dry run
On piles = [1000000000], h = 1000000000, the range starts at lo = 1, hi = 1000000000. One pile means hours = (10^9 - 1) / mid + 1. At speed 1 this is exactly 10^9, so every speed from 1 up is feasible. Every probe therefore sets hi = mid, and lo stays at 1.
| Step | lo | hi | mid | hours | hours <= h | Action |
|---|---|---|---|---|---|---|
| 1 | 1 | 1000000000 | 500000000 | 2 | yes | hi = 500000000 |
| 2 | 1 | 500000000 | 250000000 | 4 | yes | hi = 250000000 |
| 3 | 1 | 250000000 | 125000000 | 8 | yes | hi = 125000000 |
| 4 | 1 | 125000000 | 62500000 | 16 | yes | hi = 62500000 |
| 5 | 1 | 62500000 | 31250000 | 32 | yes | hi = 31250000 |
| ... | 1 | shrinking | halving | growing | yes | hi = mid |
| last | 1 | 2 | 1 | 1000000000 | yes | hi = 1 |
The run takes about 30 steps in total, and hi roughly halves each time. Late in the run hi reaches 2, then mid = 1 is feasible and hi becomes 1.
Now lo == hi == 1, the loop stops, and the function returns 1, which matches the expected output.
For contrast, take [3,6,7,11] with h = 8, where the range is 1 to 11. Speed 6 takes 6 hours, so hi = 6. Speed 3 takes 10 hours, so lo = 4.
Speed 5 takes 1+2+2+3 = 8 hours, so hi = 5. Speed 4 takes 8 hours, so hi = 4, and the answer is 4.
Complexity
| Time | O(n * log M) |
|---|---|
| Space | O(1) |
Let n be the number of piles and M be max(piles). The search range starts with M values and loses about half of them each iteration, so the loop runs at most about log2(M), which is at most 30 for M up to 10^9. Each iteration makes one pass over the n piles, so the total is O(n * log M), roughly 3 * 10^5 operations at the limits. The code keeps only lo, hi, mid and a running total, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
lo, hi = 1, max(piles)
while lo < hi:
mid = (lo + hi) // 2
hours = 0
for p in piles:
hours += (p - 1) // mid + 1 # ceil(p / mid)
if hours <= h:
hi = mid # mid works, answer is mid or smaller
else:
lo = mid + 1 # mid is too slow
return loJavaTested in our runner
import java.util.*;
class Solution {
public int minEatingSpeed(int[] piles, int h) {
int lo = 1;
int hi = 0;
for (int p : piles) {
hi = Math.max(hi, p);
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
long hours = 0; // 64-bit: the total can reach 10^13
for (int p : piles) {
hours += (p - 1) / mid + 1; // ceil(p / mid)
}
if (hours <= h) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
}C++Tested in our runner
class Solution {
public:
int minEatingSpeed(vector<int>& piles, int h) {
int lo = 1;
int hi = 0;
for (int p : piles) {
hi = max(hi, p);
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
long long hours = 0; // 64-bit: the total can reach 10^13
for (int p : piles) {
hours += (p - 1) / mid + 1; // ceil(p / mid)
}
if (hours <= h) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
};JavaScriptTested in our runner
/**
* @param {number[]} piles
* @param {number} h
* @return {number}
*/
var minEatingSpeed = function(piles, h) {
let lo = 1;
let hi = 0;
for (const p of piles) {
hi = Math.max(hi, p);
}
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
let hours = 0; // doubles are exact up to 2^53, so 10^13 is safe
for (const p of piles) {
hours += Math.floor((p - 1) / mid) + 1; // ceil(p / mid)
}
if (hours <= h) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
};GoTested in our runner
func minEatingSpeed(piles []int, h int) int {
lo, hi := 1, 0
for _, p := range piles {
if p > hi {
hi = p
}
}
for lo < hi {
mid := lo + (hi-lo)/2
hours := 0 // int is 64-bit on the judge platforms
for _, p := range piles {
hours += (p-1)/mid + 1 // ceil(p / mid)
}
if hours <= h {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}C#Tested in our runner
public class Solution {
public int minEatingSpeed(int[] piles, int h) {
int lo = 1;
int hi = 0;
foreach (int p in piles) {
hi = Math.Max(hi, p);
}
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
long hours = 0; // 64-bit: the total can reach 10^13
foreach (int p in piles) {
hours += (p - 1) / mid + 1; // ceil(p / mid)
}
if (hours <= h) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
}Common mistakes
- Using
pile / kfor the hours. Integer division rounds down, so a pile of 7 at speed 6 counts as 1 hour instead of 2. Use(pile - 1) / k + 1or(pile + k - 1) / k. - Summing hours into a 32-bit
intin Java, C++ or C#. At speed 1 with 10^4 piles of 10^9, the total is 10^13 and wraps around, which can make a failing speed look feasible. Uselongorlong long. - Setting
hi = mid - 1on a feasible speed insidewhile (lo < hi). That throws away the candidatemiditself, which may be the answer. Usehi = midwith this loop shape, or keep a separatebestvariable withlo <= hi. - Starting
loat 0. Speed 0 makes(p - 1) / middivide by zero. The minimum legal speed is 1. - Using
hi = sum(piles)or leavinghiat 10^9 without thinking. It still works but wastes iterations. Worse, ahithat is too small, such asmax(piles) - 1, can exclude the true answer when it equalsmax(piles), as in Example 2. - Computing
mid = (lo + hi) / 2with ints near 2 * 10^9. For this problem the sum stays under 2^31, but the habit breaks on other problems. Writelo + (hi - lo) / 2so the code is safe by default.
Edge cases
- One pile,
hequal to the pile size:[1000000000]withh = 1000000000returns 1. - One pile with
h = 1:[7]withh = 1returns 7, because she must eat the whole pile in a single hour. hequal topiles.length: each pile gets exactly one hour, so the answer ismax(piles). Example 2 returns 30.- All piles equal:
[5,5,5]withh = 6returns 3, since speed 3 takes 2 hours per pile and speed 2 takes 3 hours per pile. - Very large
hwith many small piles:[1,1,1]withh = 10^9returns 1, the lowest allowed speed. - Maximum size input: 10^4 piles of 10^9 with
h = 10^9. A speed of 1 needs 10^13 hours, so the answer is 10^4 and any 32-bit total in the check overflows.
Follow-ups interviewers ask
- Can you reduce the range of speeds you search?
- Yes. The speed can never be below
ceil(sum(piles) / h), because Koko eats at most k bananas per hour and every hour is used for at most k bananas. It can never be abovemax(piles). Startingloat that lower bound shrinks the range, but it does not change the O(n log M) worst-case bound. - Koko can also move to a new pile in the same hour after finishing one. How does the problem change?
- Then the leftover time in an hour carries over, so the total time is
ceil(sum(piles) / k). The feasibility check becomes O(1) after one pass to compute the sum, and the search is O(n + log M). The monotonic structure is the same, so binary search still applies. - What if there are many queries with different values of h on the same piles?
- Sort the piles once and precompute prefix sums, so a feasibility check can be answered faster than a full pass for some speeds. Alternatively, keep the per-query binary search and accept O(n log M) per query. If the number of queries is large, you can also precompute the answer for each possible hour count by sweeping speeds. That costs more memory, and it is only worth it when queries vastly outnumber piles.
Koko Eating Bananas FAQ
What is the time complexity of Koko Eating Bananas?
The binary search solution runs in O(n * log M), where n is the number of piles and M is the largest pile. It does at most about 30 feasibility checks, and each check is one pass over the piles. The brute force scan is O(n * M). Space is O(1) for both.
Why use binary search for Koko Eating Bananas?
Total hours never increase as the eating speed grows, so feasibility flips from false to true exactly once. That monotonic shape lets one test at a middle speed discard half of the remaining speeds. Without it you would test up to 10^9 speeds.
Can Koko Eating Bananas be solved in O(1) extra space?
Yes. The binary search keeps only lo, hi, mid and a running total of hours. It never copies or sorts the array, so extra space is constant.
Why is the upper bound max(piles) and not something larger?
At speed max(piles) every pile takes exactly one hour, so the total is piles.length, which the constraints guarantee is at most h. A faster speed cannot reduce any pile below one hour. So no answer above max(piles) is ever needed.
How do I write the Koko Eating Bananas solution in Python or Java?
Both follow the same plan: set lo = 1 and hi = max(piles), probe the midpoint, and sum (p - 1) // mid + 1 (Python) or (p - 1) / mid + 1 (Java). In Java, store the sum in a long. In Python, integers do not overflow, so a plain int works.
How do I compute the ceiling of a division with integers?
For positive integers, ceil(p / k) equals (p - 1) / k + 1 using integer division. It also equals (p + k - 1) / k. Avoid floating-point ceil, which is slower and can lose precision for large values.
Asked at
See which companies ask this — Pro
Related problems
- Capacity To Ship Packages Within D Days · same technique: On Answer / Condition Function
- Maximum Candies Allocated to K Children · same technique: On Answer / Condition Function
- Minimized Maximum of Products Distributed to Any Store · same technique: On Answer / Condition Function
- Minimum Limit of Balls in a Bag · same technique: On Answer / Condition Function
- Minimum Number of Days to Make m Bouquets · same technique: On Answer / Condition Function
- Median of Two Sorted Arrays · next harder, same pattern
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns