AlgoTales · Roadmap

Koko eating bananas

Advanced · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Koko must finish all piles within a set number of hours by choosing an eating speed. You search for the slowest speed that still finishes in time, by guessing a speed and checking the hours it needs.

Practical use cases

  • Web app: Minimum processing speed for a queue. A job queue has 50,000 emails to send within 8 hours. The ops team wants the lowest number of emails per minute that still finishes on time, to save on server cost. Guess a speed, work out the hours needed, and adjust. A few guesses give the answer.
  • Web app: Lecture video bandwidth. A course site must deliver several lecture files before a live class starts. The team looks for the smallest download speed that gets everything ready in time. Guessing a middle speed and recalculating the hours shows whether to go faster or slower, and saves paying for bandwidth nobody needs.
  • System: Machine throughput planning. A factory wants the slowest conveyor speed that still clears all items before the shift ends, which saves energy and wear. A few quick calculations give the answer, instead of lots of trial and error on the real machine.

The story: Koko and the Returning Guard

Koko the monkey sneaked into the fruit market at night. There were four piles of bananas: 3, 6, 7 and 11. The watchman, Mr. Pillai, had gone for chai and would be back in 8 hours. Koko wanted to finish every banana before then, but she also hated stuffing herself, so she wanted to eat as slowly as possible.

Her rule: every hour, pick one pile and eat up to k bananas from it. If the pile has fewer than k, she finishes it and rests for the remainder of the hour. So a pile of 7 at speed 3 takes 3 hours (3, 3, then 1). Which k is the smallest that finishes in 8 hours?

Koko did not test every speed. She tried the middle: speed 6 gives 1 + 1 + 2 + 2 = 6 hours, fine, so go slower. Speed 3 gives 1 + 2 + 3 + 4 = 10 hours, too slow, so go faster. Faster is always safe and slower is always risky, so the speeds form a "no, no, yes, yes" line, and binary search finds the first yes: 4 bananas an hour. Guess the speed, count the hours, halve the range.

How to spot this problem, and where you need it

You must pick the smallest rate, speed or capacity that gets all the work done within a time limit, and you can easily work out how long any chosen rate would take.

Signs you need it

  • The problem says "minimum eating speed", "finish within h hours" or "smallest rate that still completes in time".
  • Higher speed always finishes sooner, so the answer switches cleanly from too slow to fast enough.
  • You can compute the hours for a guessed speed with one pass over the piles, but you cannot solve for the speed directly.

Where to use it in a project

  • Sizing queue workers, API rate limits or download speeds to meet a deadline at the least cost.
  • Capacity planning for batch jobs, such as email blasts or report generation before a cut-off.

The solution

The speed lies between 1 and the biggest pile. Guess the middle speed. Add up the hours needed: for each pile, divide by the speed and round up. If the total is within the limit, the speed is enough, so try slower; if not, try faster. Repeat until the range closes. The final speed is the slowest that still finishes in time.

Payoff: Before: running every speed from 1 to 1,000,000. After: about 20 guesses, so the right setting is found right away.

Explain it like I am 8

You have homework pages and the bell rings in 8 hours. You wonder, "Can I read just 4 pages an hour?" Count the hours: if you finish in time, maybe you can go slower. If not, you must read faster. Keep trying the middle speed.

How it works, step by step

  1. The range of speeds: slowest is 1, fastest we ever need is the biggest pile (then each pile takes one hour).
  2. For a guessed speed k, count the hours: for each pile it is the pile size divided by k, rounded up. Add them all.
  3. If the total hours <= h, the speed is fast enough: high = mid (try slower). Otherwise low = mid + 1 (go faster).
  4. Stop when low meets high. That is the slowest speed that works.
  5. Rounding up without a function: (pile + k - 1) divided by k using whole-number division.

The code in four languages

PHP

<?php
// Hours Koko needs at speed $k: each pile rounds UP to whole hours.
function hoursNeeded(array $piles, int $k): int {
    $hours = 0;
    foreach ($piles as $p) {
        $hours += intdiv($p + $k - 1, $k);      // round up p / k
    }
    return $hours;
}

// Smallest eating speed that finishes within $h hours.
function minEatingSpeed(array $piles, int $h): int {
    $low = 1;                                    // slowest possible
    $high = max($piles);                         // fast enough: one pile per hour
    while ($low < $high) {
        $mid = intdiv($low + $high, 2);
        if (hoursNeeded($piles, $mid) <= $h) {
            $high = $mid;                        // fast enough: try slower
        } else {
            $low = $mid + 1;                     // too slow: speed up
        }
    }
    return $low;
}

echo minEatingSpeed([3, 6, 7, 11], 8), "\n";    // 4
echo minEatingSpeed([30, 11, 23, 4, 20], 5), "\n";   // 30

JavaScript

// Hours Koko needs at speed k: each pile rounds UP to whole hours.
function hoursNeeded(piles, k) {
  let hours = 0;
  for (const p of piles) {
    hours += Math.ceil(p / k);               // round up p / k
  }
  return hours;
}

// Smallest eating speed that finishes within h hours.
function minEatingSpeed(piles, h) {
  let low = 1;                               // slowest possible
  let high = Math.max(...piles);             // fast enough: one pile per hour
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (hoursNeeded(piles, mid) <= h) {
      high = mid;                            // fast enough: try slower
    } else {
      low = mid + 1;                         // too slow: speed up
    }
  }
  return low;
}

console.log(minEatingSpeed([3, 6, 7, 11], 8));        // 4
console.log(minEatingSpeed([30, 11, 23, 4, 20], 5));  // 30

Java

public class Main {
    // Hours Koko needs at speed k: each pile rounds UP to whole hours.
    static int hoursNeeded(int[] piles, int k) {
        int hours = 0;
        for (int p : piles) {
            hours += (p + k - 1) / k;               // round up p / k
        }
        return hours;
    }

    // Smallest eating speed that finishes within h hours.
    static int minEatingSpeed(int[] piles, int h) {
        int biggest = 0;
        for (int p : piles) biggest = Math.max(biggest, p);
        int low = 1;                                // slowest possible
        int high = biggest;                         // fast enough: one pile per hour
        while (low < high) {
            int mid = low + (high - low) / 2;
            if (hoursNeeded(piles, mid) <= h) {
                high = mid;                         // fast enough: try slower
            } else {
                low = mid + 1;                      // too slow: speed up
            }
        }
        return low;
    }

    public static void main(String[] args) {
        System.out.println(minEatingSpeed(new int[]{3, 6, 7, 11}, 8));         // 4
        System.out.println(minEatingSpeed(new int[]{30, 11, 23, 4, 20}, 5));   // 30
    }
}

Go

package main

import (
	"fmt"
	"slices"
)

// hoursNeeded: hours Koko needs at speed k; each pile rounds UP to whole hours.
func hoursNeeded(piles []int, k int) int {
	hours := 0
	for _, p := range piles {
		hours += (p + k - 1) / k // round up p / k
	}
	return hours
}

// minEatingSpeed returns the smallest eating speed that finishes within h hours.
func minEatingSpeed(piles []int, h int) int {
	low := 1                  // slowest possible
	high := slices.Max(piles) // fast enough: one pile per hour
	for low < high {
		mid := low + (high-low)/2
		if hoursNeeded(piles, mid) <= h {
			high = mid // fast enough: try slower
		} else {
			low = mid + 1 // too slow: speed up
		}
	}
	return low
}

func main() {
	fmt.Println(minEatingSpeed([]int{3, 6, 7, 11}, 8))       // 4
	fmt.Println(minEatingSpeed([]int{30, 11, 23, 4, 20}, 5)) // 30
}

Time: O(n log M) · Extra space: O(1). M is the biggest pile. About log M speeds are tried and each check adds up n piles. Assumes h is at least the number of piles.

Watch out for

  • Rounding down instead of up: a pile of 7 at speed 3 takes 3 hours, not 2.
  • Letting Koko switch piles mid-hour. She eats from only one pile each hour.
  • Starting low at 0, which causes division by zero.

Quick check

  1. At speed 3, a pile of 7 bananas takes...
    • 2 hours
    • 4 hours
    • 3 hours
  2. The total hours at the guessed speed is 10 and the guard is back in 8. Next?
    • Go faster: low = mid + 1
    • Go slower: high = mid
    • Give up
  3. Why is the largest pile a safe upper limit?
    • Every pile then takes one hour
    • Monkeys eat fast
    • It is the average