Koko Eating Bananas (LeetCode 875): Solution and Explanation

Medium
Array
Binary Search

There are several piles of bananas and h hours available. Each hour Koko picks one pile and eats up to k bananas from it, and if the pile has fewer she finishes it and waits out the hour. Find the smallest integer speed k that lets her finish every pile within h hours.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Start by asking how long a given speed takes. At speed k, a pile of p bananas needs ceil(p / k) hours, because a partial last hour still counts as a full hour. Summing that over every pile tells you whether speed k works. So the brute force is to try k = 1, 2, 3 and so on until the total hours fit within h. With piles as large as a billion, that can mean a billion candidate speeds, each costing a full pass over the piles.

The observation that unlocks the problem is monotonicity. If Koko can finish at speed k, she can certainly finish at any faster speed, since each pile takes the same or fewer hours. And if she cannot finish at speed k, no slower speed works either. The feasible speeds form a contiguous range of the form [answer, infinity), and you want its left edge.

Whenever a yes or no question flips exactly once as a number increases, you can binary search for the flip point instead of scanning. The search range is from 1, the slowest meaningful speed, to max(piles), because eating faster than the largest pile never saves any hours: every pile already takes one hour at that speed.

At each step pick the middle speed, compute the hours it needs, and if it fits within h, record it and search the slower half for something better. Otherwise search the faster half. This pattern, binary search on the answer combined with a greedy feasibility check, shows up in many problems about minimizing a capacity or a rate.

Approach: Binary search on eating speed

  1. Set the search range l = 1, r = max(piles), and initialize res = r, which is always feasible.
  2. While l <= r, pick the middle speed k = (l + r) // 2.
  3. Compute hours as the sum of math.ceil(p / k) over all piles.
  4. If hours <= h, speed k works, so set res = min(res, k) and try slower speeds with r = k - 1.
  5. Otherwise k is too slow, so search faster speeds with l = k + 1.
  6. When the range is empty, return res.

Step-by-step example

piles = [3,6,7,11], h = 8
  1. The range is 1 to 11. Middle speed 6 takes 1 + 1 + 2 + 2 = 6 hours, which fits, so res = 6 and the range becomes 1 to 5.
  2. Middle speed 3 takes 1 + 2 + 3 + 4 = 10 hours, more than 8, so the range becomes 4 to 5.
  3. Middle speed 4 takes 1 + 2 + 2 + 3 = 8 hours, which fits exactly, so res = 4 and the range becomes 4 to 3.
  4. The range is empty, so the answer is 4.

Code: Python, Java, C++

1class Solution:
2    def minEatingSpeed(self, piles: List[int], h: int) -> int:
3        l, r = 1, max(piles)
4        res = r
5        
6        while l <= r:
7            k = (l + r) // 2
8            hours = 0
9            for p in piles:
10                hours += math.ceil(p / k)
11                
12            if hours <= h:
13                res = min(res, k)
14                r = k - 1
15            else:
16                l = k + 1
17        return res

Time and space complexity

Time

O(n log m)

Here n is the number of piles and m is the largest pile. Binary search takes O(log m) rounds, and each round sums the hours over all n piles.

Space

O(1)

Only the search bounds, the current speed and the hour counter are stored.

Other approaches

Linear scan over speeds (time O(n × m), space O(1))

Try speeds from 1 upward and return the first that fits within h. It is correct and easy to reason about, but it can take up to max(piles) iterations, which times out for large piles.

Tighter lower bound (time O(n log m), space O(1))

Start the search at ceil(sum(piles) / h) instead of 1, since Koko must eat at least that many bananas per hour on average. It shrinks the search range a little but does not change the asymptotic cost.

Common mistakes

  • Using floor division p // k for the hours. A pile of 7 at speed 4 takes 2 hours, not 1.
  • Starting the search at 0, which leads to division by zero when computing hours.
  • Setting r = k instead of k - 1 together with while l <= r, which can loop forever once l equals r.
  • Summing hours in a 32-bit integer in Java or C++. With many piles at speed 1 the total can exceed the 32-bit range, so use a long.

Frequently asked questions

Why does binary search work for Koko Eating Bananas?

Feasibility is monotonic in the speed. If a speed finishes in time, every faster speed also does, so there is a single boundary between too slow and fast enough, and binary search finds it.

What are the bounds for the binary search?

The lower bound is 1 banana per hour and the upper bound is the largest pile. Going faster than the largest pile cannot help because every pile already takes exactly one hour.

What is the time complexity?

It is O(n log m), where n is the number of piles and m is the largest pile. Each of the log m search steps does a linear pass over the piles.

How do you compute the ceiling without floating point?

Use (p + k - 1) // k in integer arithmetic. It gives the same result as ceil(p / k) without any rounding concerns on large values.