Koko Eating Bananas solution explained

Koko Eating Bananas is solved by binary searching the eating speed instead of an array: any speed from 1 to the largest pile is a candidate, the hours needed at speed k is the sum of ceil(pile / k), and that total only goes down as k goes up. So the smallest speed that fits the hour limit is a boundary you can find in O(n log m) time, where n is the number of piles and m the largest pile.

By Published 8 min read

The problem, without the story

There are several piles of items, each with a known size. Every hour, you pick one pile and remove up to k items from it. If the pile has fewer than k left, you finish it, and the rest of that hour is wasted; you cannot move on to another pile in the same hour. You have h hours in total, and h is at least the number of piles, so finishing is always possible at some speed. Return the smallest whole-number speed k that clears every pile within h hours.

The name comes from the version of the story where a character eats bananas before the keepers come back. The story does not matter. What matters is the shape: a minimum value you must choose, and a quick way to check whether a given value is good enough.

Pile sizes invented for this page, answers produced by the tested code
PilesHours allowedSlowest speed that worksWhy
[5, 9, 4]642 + 3 + 1 = 6 hours; speed 3 needs 7
[5, 9, 4]39One hour per pile, so the biggest pile sets the speed
[12]43Four hours of 3
[10, 10]210Again one hour per pile
[7, 30, 11, 2]881 + 4 + 2 + 1 = 8 hours; speed 7 needs 9
Pile sizes invented for this page, answers produced by the tested code. Scroll sideways on a small screen.

Why it is a good interview question

Nothing in the prompt says sorted array, so candidates who think of binary search only as a way to find a value in a list do not see it. The interviewer is checking whether you can recognize that the answer itself lives in an ordered range, and whether you can write the feasibility check and the boundary search without off-by-one errors. The same template solves shipping capacity, splitting work among a fixed number of people and minimum-time scheduling questions, so it is a high-value pattern to own.

The building block: hours at a given speed

At speed k, a pile of size p takes ceil(p / k) hours. Sum that over all piles and compare with h. With integers, ceil(p / k) is (p + k - 1) // k, which avoids floating point. This check is O(n) for n piles.

def hours_needed(piles, speed):
    return sum((pile + speed - 1) // speed for pile in piles)  # ceiling division
Hours needed at one speed, using integer ceiling division.

Brute force: try speeds in order

Start at speed 1 and go up until the hours fit. The first speed that fits is the answer. In the worst case you try every speed up to the largest pile m, each check costing O(n), so O(n · m) time. With large piles that is far too slow, but it is a correct reference and a good opening sentence.

def slowest_speed_linear(piles, limit):
    speed = 1
    while hours_needed(piles, speed) > limit:
        speed += 1
    return speed
Try every speed from 1 upward, O(n · m).

Binary search over speeds

Two facts make this searchable. First, the answer is between 1 and the largest pile: at the largest pile's size, every pile takes exactly one hour, and h is at least the number of piles. Second, the check is monotone. If speed k finishes in time, any faster speed also finishes in time, because no pile can take longer at a higher speed. So the candidates line up as no, no, no, yes, yes, yes, and you want the first yes. That is the boundary-finding form of binary search.

def slowest_speed(piles, limit):
    low, high = 1, max(piles)  # max(piles) always finishes in len(piles) hours
    while low < high:
        mid = (low + high) // 2
        if hours_needed(piles, mid) <= limit:
            high = mid  # fast enough: the answer is mid or slower
        else:
            low = mid + 1  # too slow: the answer is faster than mid
    return low
Python: find the first speed that fits, O(n log m).
function slowestSpeed(piles, limit) {
  const hoursAt = (speed) =>
    piles.reduce((sum, pile) => sum + Math.ceil(pile / speed), 0);
  let low = 1;
  let high = piles.reduce((a, b) => Math.max(a, b), 1);
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (hoursAt(mid) <= limit) high = mid;
    else low = mid + 1;
  }
  return low;
}
JavaScript: the same search, with the check inline.

The JavaScript version finds the largest pile with reduce rather than Math.max(...piles), because spreading a very long array into function arguments can exceed the engine's argument limit. Math.ceil(pile / speed) is safe here since piles and speeds are integers well inside the range where JavaScript division is exact enough to round correctly.

A trace

Piles [7, 30, 11, 2], 8 hours allowed
lowhighmidHours at midDecision
130155Fits, so high = 15
11588Fits exactly, so high = 8
18414Too slow, so low = 5
58610Too slow, so low = 7
7879Too slow, so low = 8
88Range has one value: answer 8
Piles [7, 30, 11, 2], 8 hours allowed. Scroll sideways on a small screen.

Notice that speed 8 was found to work on the second step, but the search kept going. It had to confirm that nothing slower also works, which is exactly what the half-open loop does by keeping high = mid instead of returning early.

Cost

n piles, largest pile m
ApproachTimeExtra space
Every speed from 1 upwardO(n · m)O(1)
Binary search on speedO(n log m)O(1)
n piles, largest pile m. Scroll sideways on a small screen.

You can tighten the starting range: the answer is at least ceil(total items / h), since even with no wasted time you need that rate. It does not change the big-O bound, but mentioning it shows you are thinking about the problem rather than reciting a template.

Edge cases

  • Hours equal to the number of piles: the answer is the largest pile.
  • Lots of spare hours: the answer can drop to 1.
  • A single pile: the answer is ceil(pile / h).
  • Very large piles: the sum of hours can exceed a 32-bit int in C++ or Java at low speeds. Use 64-bit totals.
  • Piles of size 1 everywhere: any speed works, so 1.

Where answers go wrong

  • Using pile / k with real division and forgetting to round up, which undercounts hours.
  • Starting the search at 0, which divides by zero on the first check.
  • Returning as soon as a speed fits instead of continuing to look for a slower one.
  • Searching up to the sum of all piles. It is still correct, just a wider range than needed; the largest pile is the tight upper bound.
  • Not explaining why the check is monotone. Without that, binary search is an unjustified leap.

How to explain it out loud

Fictional example

Spotting binary search where there is no sorted array
Candidate
For a fixed speed I can compute the hours in one pass: each pile takes the ceiling of its size over the speed. So checking one speed is linear.
Candidate
If a speed works, every faster speed works too. So the speeds from 1 to the largest pile go from 'too slow' to 'fast enough' exactly once, and I want the first 'fast enough'.
Interviewer
Why is the largest pile a safe upper bound?
Candidate
At that speed each pile takes one hour, and we have at least one hour per pile. So the answer is somewhere in that range, and binary search over it costs log of the largest pile checks, each linear.

Same pattern, other problems

  • Smallest daily capacity to ship packages in order within d days. Candidates run from the largest package to the total weight; the check simulates the days.
  • Split an array into k parts minimizing the largest part sum. Same check, phrased as 'can I split so that no part exceeds x?'.
  • Earliest day on which enough flowers have bloomed to make m bouquets. Search over days; the check counts bouquets.

The half-open loop used here is explained step by step in Binary Search, under the first-position variant. Search a 2D Matrix is the opposite move, applying binary search to stored data with an unusual shape. Find Minimum in Rotated Sorted Array is another boundary search, where the yes/no question is 'is this position past the rotation point?'. All walkthroughs are listed on the coding problems hub.

Drilling this pattern with Natively

The win on this problem is recognizing the pattern quickly, so practice saying 'answer range plus monotone check' within the first minute. Natively keeps a transcript of each mock round on your Mac or Windows computer, which shows how long it actually took you to get there. During practice it can also read a word problem like this from a screenshot and point out that the answer space is searchable. The AI assistant for coding interviews page explains the coding features.

Questions people ask

How do you solve Koko Eating Bananas?

Binary search the speed between 1 and the largest pile. For each candidate speed, add up the ceiling of each pile divided by the speed; if the total fits the hour limit, try slower speeds, otherwise try faster ones.

Why does binary search work for Koko Eating Bananas?

Hours needed never increase as the speed goes up, so the speeds go from too slow to fast enough exactly once. Binary search finds that boundary.

What is the time complexity of Koko Eating Bananas?

O(n log m), where n is the number of piles and m the largest pile: about log m candidate speeds, each checked in one pass over the piles.

What is binary search on the answer?

A technique for problems that ask for the smallest or largest value meeting a condition. If the condition is monotone over a range of candidates, binary search the range with the condition as the comparison.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP