Skip to content
mlmentorship

Koko Eating Bananas

Find the slowest eating speed that finishes all piles within the time limit.

Published · 14 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Koko Eating Bananas

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonempty list piles of positive integers and an integer deadline hours >= len(piles). Output. Return the minimum positive integer speed, measured in bananas per hour, that finishes all piles by the deadline. Rules. During one hour, work on only one pile and consume up to the chosen speed. Finishing a smaller remainder still uses the whole hour; unused capacity cannot transfer to another pile. Use one speed throughout and preserve the piles. The reference assumes a feasible deadline. Example. Piles [3, 6, 7, 11] with 8 hours return 4. At that speed the piles take 1, 2, 2, and 3 hours, totaling 8.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Binary-search the first speed whose ceiling-division total is at most 8 hours.

Problem trace

Speed 4 passes the deadline; every lower speed fails

Worked example: a passing speed rules out the need for faster candidatesFor piles (3,6,7,11) and eight hours, speed 3 needs ten hours. Speed 4 needs eight and is feasible; every lower speed fails.A partial final hour still occupiesone hour boxSpeed 3; piles keep their separatehour counts336337331113332Ten occupied hours miss theeight-hour deadlineSpeed 4; piles keep their separatehour counts3364274311443Eight occupied hours meet thedeadline
Read it this way: For piles (3,6,7,11) and eight hours, speed 3 needs ten hours. Speed 4 needs eight and is feasible; every lower speed fails. At speed four, does the last three-banana remainder of pile eleven cost zero hours or one?
Full interview answer 14 min read
Reading depth

Find the smallest constant eating speed that finishes every banana pile within a fixed number of hours.

Problem

Input. A nonempty list piles of positive integers and an integer deadline hours >= len(piles).

Output. Return the minimum positive integer speed, measured in bananas per hour, that finishes all piles by the deadline.

Rules. During one hour, work on only one pile and consume up to the chosen speed. Finishing a smaller remainder still uses the whole hour; unused capacity cannot transfer to another pile. Use one speed throughout and preserve the piles. The reference assumes a feasible deadline.

Example. Piles [3, 6, 7, 11] with 8 hours return 4. At that speed the piles take 1, 2, 2, and 3 hours, totaling 8.

Picture: Search Speeds, Not Pile Indices

Problem trace

Speed 4 passes the deadline; every lower speed fails

Input and goalFind the slowest eating speed that finishes all piles within the time limit.
Test the initial midpointSpeed 6 takes 1+1+2+2=6 hours. It meets the eight-hour limit; set right=6.
left1021324354speed65768798109right1110
inputpiles [3,6,7,11], hours 8testedk=6: ceil(3/6)+ceil(6/6)+ceil(7/6)+ceil(11/6)=1+1+2+2=6decision6 <= 8: right = 6
left
0
speed
5
right
10

Recognize it
The answer is numeric, bounded from 1 to max(piles), and feasibility changes only once: if speed k finishes in time, every faster speed also finishes.
Keep true
The minimum feasible speed always remains in inclusive [left, right]. An infeasible midpoint and every slower speed are removed; a feasible midpoint is retained as right.
Reuse it
For capacity, rate, and threshold problems, define a monotone yes/no test, choose bounds that contain the answer, and retain the midpoint on the side that may hold the first true value.
Speed 6 takes 1+1+2+2=6 hours. It meets the eight-hour limit; set right=6. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: What proves speed 4 is the minimum, rather than merely one speed that meets eight hours?
Reference drawing

Problem trace

Speed 4 passes the deadline; every lower speed fails

Worked example: a passing speed rules out the need for faster candidatesFor piles (3,6,7,11) and eight hours, speed 3 needs ten hours. Speed 4 needs eight and is feasible; every lower speed fails.A partial final hour still occupiesone hour boxSpeed 3; piles keep their separatehour counts336337331113332Ten occupied hours miss theeight-hour deadlineSpeed 4; piles keep their separatehour counts3364274311443Eight occupied hours meet thedeadline
Execution trace
Input and goalFind the slowest eating speed that finishes all piles within the time limit.
Test the initial midpointSpeed 6 takes 1+1+2+2=6 hours. It meets the eight-hour limit; set right=6.
left1021324354speed65768798109right1110
inputpiles [3,6,7,11], hours 8testedk=6: ceil(3/6)+ceil(6/6)+ceil(7/6)+ceil(11/6)=1+1+2+2=6decision6 <= 8: right = 6
left
0
speed
5
right
10

Recognize it
The answer is numeric, bounded from 1 to max(piles), and feasibility changes only once: if speed k finishes in time, every faster speed also finishes.
Keep true
The minimum feasible speed always remains in inclusive [left, right]. An infeasible midpoint and every slower speed are removed; a feasible midpoint is retained as right.
Reuse it
For capacity, rate, and threshold problems, define a monotone yes/no test, choose bounds that contain the answer, and retain the midpoint on the side that may hold the first true value.
Speed 6 takes 1+1+2+2=6 hours. It meets the eight-hour limit; set right=6. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: What proves speed 4 is the minimum, rather than merely one speed that meets eight hours?
Read it this way: For piles (3,6,7,11) and eight hours, speed 3 needs ten hours. Speed 4 needs eight and is feasible; every lower speed fails. At speed four, does the last three-banana remainder of pile eleven cost zero hours or one?
speedHours by pileTotalMove
61 + 1 + 2 + 26Keep candidate: right = 6
31 + 2 + 3 + 410Discard slower speeds: left = 4
51 + 2 + 2 + 38Keep candidate: right = 5
41 + 2 + 2 + 38Keep candidate: right = 4

At speed , required time is . Each ceiling term is nonincreasing in , giving a false-to-true feasibility boundary. Under the reference contract, speed max(piles) is feasible: each pile needs one hour. The minimum stays within [left, right]; an infeasible midpoint is removed, but a feasible midpoint remains a possible answer.

Code

def min_eating_speed(piles: list[int], hours: int) -> int:
   left, right = 1, max(piles)

   while left < right:
      speed = (left + right) // 2
      time = sum((pile + speed - 1) // speed for pile in piles)
      if time <= hours:
         right = speed
      else:
         left = speed + 1
   return left

The bounds meet at 4; speed 3 needs 10 hours, proving minimality rather than feasibility alone. Integer ceiling division avoids floating-point rounding. For piles and maximum , there are probes, each costing . Auxiliary space is under unit-cost arithmetic.

Change 1: Expose Impossible and Empty Cases

New task. Return None when impossible and 0 when no piles exist.

Picture and change. Keep positive piles and a nonnegative integer deadline. Guard before calling the retained reference.

Code. Place this wrapper after min_eating_speed:

def min_speed_or_none(piles, hours):
   if not piles:
      return 0
   if hours < len(piles):
      return None
   return min_eating_speed(piles, hours)

Check. Four piles with 3 hours return None; ([], 0) returns 0; the main input returns 4.

Use when. The API accepts deadlines outside the guaranteed-feasible contract.

Change 2: Add Fixed Per-Pile Setup

New task. Each pile also needs setup nonnegative integer hours, independent of speed.

Picture and change. Subtract total setup before the same monotone search. Retain the reference function above this wrapper.

Code.

def min_speed_with_setup(piles, hours, setup):
   if not piles:
      return 0
   eating_hours = hours - setup * len(piles)
   if eating_hours < len(piles):
      return None
   return min_eating_speed(piles, eating_hours)

Check. Twelve hours minus four setup hours leaves eight: answer 4. For [3, 6], 3 hours, setup 1, return None.

Use when. Added work changes feasibility without changing its monotone direction.

Failure: Returning an Infeasible Upper Bound

Four positive piles need at least four hours. The unguarded reference does not solve a three-hour deadline.

Transfer Check

What changes if faster speeds add a speed-dependent setup penalty?

Reasoned Answer

Total time may cease to be monotone. Re-prove the boundary property and feasible bounds before reusing binary search.

Preserve the First Feasible Candidate

Unlike exact index lookup, equality with the deadline does not settle minimality. Setting right = speed - 1 can discard the only minimum candidate; keep it with right = speed. With left < right, the midpoint is strictly below right, so either branch shrinks the candidate interval.

Empty input would make the original max([]) fail; impossibility can make it return an infeasible maximum. The wrappers expand the output contract without changing the original function’s guaranteed-feasible domain. They rely on their stated input preconditions, not runtime validation of arbitrary objects.

This discrete scheduling model is not a real serving-latency or fleet-SLO guarantee. Compare candidate-interval search when defining and proving new boundary contracts.