15% off all plans & roadmaps Use code

See plans

Koko Eating Bananas

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^4
  • piles.length <= h <= 10^9
  • 1 <= 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 <= h guarantees at least one hour per pile. That means speed max(piles) always works, since every pile then takes exactly one hour. So the answer always exists and is at most max(piles).
  • piles.length up 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Compute hi = max(piles), the largest speed worth trying.
  2. For each k from 1 to hi, set hours = 0.
  3. For each pile p, add ceil(p / k) to hours. Use integer math: (p - 1) / k + 1.
  4. If hours <= h, return k.
  5. The loop always returns by k = hi, so no fallback is needed beyond returning hi.

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^9 hours.
  • 10^9 <= 10^9 is 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

TimeO(n * M)
SpaceO(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 hi
On Answer / Condition Function pattern infographic for Koko Eating Bananas

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

  1. Set lo = 1 and hi = max(piles). Speed hi is always feasible because piles.length <= h.
  2. While lo < hi, compute mid = lo + (hi - lo) / 2.
  3. Compute hours as the sum of (p - 1) / mid + 1 over all piles, using a 64-bit total.
  4. If hours <= h, then mid works and a smaller speed might too, so set hi = mid.
  5. Otherwise mid is too slow, so set lo = mid + 1.
  6. When the loop ends, lo == hi. Return lo.

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.

Steplohimidhourshours <= hAction
1110000000005000000002yeshi = 500000000
215000000002500000004yeshi = 250000000
312500000001250000008yeshi = 125000000
411250000006250000016yeshi = 62500000
51625000003125000032yeshi = 31250000
...1shrinkinghalvinggrowingyeshi = mid
last1211000000000yeshi = 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

TimeO(n * log M)
SpaceO(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 lo

Common mistakes

  • Using pile / k for 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 + 1 or (pile + k - 1) / k.
  • Summing hours into a 32-bit int in 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. Use long or long long.
  • Setting hi = mid - 1 on a feasible speed inside while (lo < hi). That throws away the candidate mid itself, which may be the answer. Use hi = mid with this loop shape, or keep a separate best variable with lo <= hi.
  • Starting lo at 0. Speed 0 makes (p - 1) / mid divide by zero. The minimum legal speed is 1.
  • Using hi = sum(piles) or leaving hi at 10^9 without thinking. It still works but wastes iterations. Worse, a hi that is too small, such as max(piles) - 1, can exclude the true answer when it equals max(piles), as in Example 2.
  • Computing mid = (lo + hi) / 2 with ints near 2 * 10^9. For this problem the sum stays under 2^31, but the habit breaks on other problems. Write lo + (hi - lo) / 2 so the code is safe by default.

Edge cases

  • One pile, h equal to the pile size: [1000000000] with h = 1000000000 returns 1.
  • One pile with h = 1: [7] with h = 1 returns 7, because she must eat the whole pile in a single hour.
  • h equal to piles.length: each pile gets exactly one hour, so the answer is max(piles). Example 2 returns 30.
  • All piles equal: [5,5,5] with h = 6 returns 3, since speed 3 takes 2 hours per pile and speed 2 takes 3 hours per pile.
  • Very large h with many small piles: [1,1,1] with h = 10^9 returns 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 above max(piles). Starting lo at 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

Practise it