Koko Eating Bananas

Problem and examples

Koko the monkey loves bananas. She has a list of banana piles, and she wants to eat all of them within h hours. Each hour, Koko chooses any pile and eats up to k bananas from it. If the pile has fewer than k bananas, she eats the entire pile and moves on.

Your task is to help Koko determine the minimum integer eating speed k such that she can finish all the bananas in at most h hours.

If the list of banana piles is empty, return 0 as there are no bananas to eat.

Banana Piles Hours (h) Minimum Eating Speed (k) Description
[3, 6, 7, 11] 8 4 Koko can eat all piles in 8 hours if she eats 4 bananas/hour
[30, 11, 23, 4, 20] 5 30 She must eat very fast to finish in just 5 hours
[30, 11, 23, 4, 20] 6 23 With 6 hours, speed of 23 is sufficient
[1, 1, 1, 1] 4 1 Minimum speed needed is 1 banana/hour
[1000000000] 2 500000000 Single large pile, she must eat half in each hour
[] 5 0 No piles to eat, so minimum speed is 0
[10] 1 10 Only one pile, must eat all in one hour

Explore Koko Eating Bananas

Load an example or enter your own input. Use the player controls to follow each change.

Understanding the Problem

We are given a list of banana piles, and a total number of hours h within which Koko must finish eating all the bananas. Each hour, Koko chooses one pile and eats up to k bananas from it. If the pile has fewer than k bananas, she eats all of them and doesn’t continue to another pile in the same hour.

The goal is to find the minimum integer speed k such that Koko can finish eating all the bananas within h hours. This is essentially an optimization problem — we want the smallest value of k for which the total time taken does not exceed h.

Step-by-Step Solution with Example

Step 1: Understand how time is calculated

If Koko eats at a speed k, then for each pile, the number of hours she needs is ceil(pile / k). We need to compute this for all piles and add it up to find the total time.

Step 2: Choose an example

Let's say the piles are [3, 6, 7, 11] and h = 8. Koko must eat all bananas in at most 8 hours.

Step 3: Identify possible range for k

The minimum speed is 1 banana per hour. The maximum speed is the largest pile, 11, because if she can finish the biggest pile in one hour, she can finish any pile in one hour.

Step 4: Use Binary Search to find the minimum k

We now perform binary search between 1 and 11:

  • Mid = 6: Total time = ceil(3/6) + ceil(6/6) + ceil(7/6) + ceil(11/6) = 1 + 1 + 2 + 2 = 6 (less than 8) → try smaller speed.
  • Mid = 3: Total time = ceil(3/3) + ceil(6/3) + ceil(7/3) + ceil(11/3) = 1 + 2 + 3 + 4 = 10 (too much) → try higher speed.
  • Mid = 4: Total time = 1 + 2 + 2 + 3 = 8 (just fits) → try smaller speed to optimize further.
  • Mid = 3: already tested, doesn’t work → so answer is 4.

Step 5: Return the result

The minimum speed k that allows Koko to finish within h = 8 hours is 4.

Edge Cases

  • Exact Fit: If h equals the number of piles, then Koko must eat one pile per hour. So the speed must be at least as large as the largest pile.
  • Very Large h: If h is very high, Koko can eat slowly. Even speed = 1 might be enough.
  • Only One Pile: Then the speed is just ceil(pile / h).
  • No Piles: If the list is empty, return 0 since there's nothing to eat.
  • All piles are size 1: The total time is equal to the number of piles, and any k ≥ 1 would work if h is enough.

Finally

This problem is a great example of combining simulation with optimization using binary search. The key insight is understanding how ceil(pile / k) affects total time and narrowing the search space smartly. Always consider edge cases — especially empty input, minimum and maximum bounds — when crafting such a solution.

  1. Initialize low = 1, high = max(piles), and answer = max(piles).
  2. While low ≤ high:
  3. → Compute mid = (low + high) / 2 as current eating speed.
  4. → For each pile, calculate hours = ceil(pile / mid).
  5. → Sum total hours for all piles.
  6. → If total hours ≤ h: update answer = mid, and search left by setting high = mid - 1.
  7. → Else, search right with low = mid + 1.
  8. Return answer as the minimum valid eating speed.

Implementation and efficiency

C implementation

#include <stdio.h>
#include <math.h>

int max(int arr[], int n) {
  int m = arr[0];
  for (int i = 1; i < n; i++)
    if (arr[i] > m) m = arr[i];
  return m;
}

int minEatingSpeed(int piles[], int n, int h) {
  int low = 1, high = max(piles, n), answer = high;
  while (low <= high) {
    int mid = low + (high - low) / 2;
    int hours = 0;
    for (int i = 0; i < n; i++)
      hours += (piles[i] + mid - 1) / mid;

    if (hours <= h) {
      answer = mid;
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  return answer;
}

int main() {
  int piles[] = {3, 6, 7, 11};
  int h = 8;
  int n = sizeof(piles) / sizeof(piles[0]);
  printf("%d\n", minEatingSpeed(piles, n, h));
  return 0;
}

C++ implementation

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;

int minEatingSpeed(vector<int>& piles, int h) {
  int low = 1, high = *max_element(piles.begin(), piles.end());
  int answer = high;

  while (low <= high) {
    int mid = low + (high - low) / 2;
    int hours = 0;
    for (int pile : piles) {
      hours += ceil((double)pile / mid);
    }
    if (hours <= h) {
      answer = mid;
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  return answer;
}

int main() {
  vector<int> piles = {3, 6, 7, 11};
  int h = 8;
  cout << minEatingSpeed(piles, h) << endl;
  return 0;
}

Python implementation

import math

def minEatingSpeed(piles, h):
    low, high = 1, max(piles)
    answer = high

    while low <= high:
        mid = (low + high) // 2
        hours = sum(math.ceil(p / mid) for p in piles)

        if hours <= h:
            answer = mid
            high = mid - 1
        else:
            low = mid + 1

    return answer

print(minEatingSpeed([3, 6, 7, 11], 8))

Java implementation

import java.util.*;

public class KokoEatingBananas {
  public static int minEatingSpeed(int[] piles, int h) {
    int low = 1, high = Arrays.stream(piles).max().getAsInt();
    int answer = high;

    while (low <= high) {
      int mid = low + (high - low) / 2;
      int hours = 0;
      for (int pile : piles) {
        hours += (pile + mid - 1) / mid;
      }

      if (hours <= h) {
        answer = mid;
        high = mid - 1;
      } else {
        low = mid + 1;
      }
    }

    return answer;
  }

  public static void main(String[] args) {
    int[] piles = {3, 6, 7, 11};
    int h = 8;
    System.out.println(minEatingSpeed(piles, h));
  }
}

JavaScript implementation

function minEatingSpeed(piles, h) {
  let low = 1;
  let high = Math.max(...piles);
  let answer = high;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    let hours = 0;
    for (let pile of piles) {
      hours += Math.ceil(pile / mid);
    }
    if (hours <= h) {
      answer = mid;
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  return answer;
}

console.log(minEatingSpeed([3, 6, 7, 11], 8));

Go implementation

package main

import (
  "fmt"
  "math"
)

func minEatingSpeed(piles []int, h int) int {
  max := func(arr []int) int {
    m := arr[0]
    for _, v := range arr {
      if v > m {
        m = v
      }
    }
    return m
  }

  low, high := 1, max(piles)
  answer := high

  for low <= high {
    mid := (low + high) / 2
    hours := 0
    for _, pile := range piles {
      hours += int(math.Ceil(float64(pile) / float64(mid)))
    }

    if hours <= h {
      answer = mid
      high = mid - 1
    } else {
      low = mid + 1
    }
  }
  return answer
}

func main() {
  piles := []int{3, 6, 7, 11}
  h := 8
  fmt.Println(minEatingSpeed(piles, h))
}

Rust implementation

fn min_eating_speed(piles: &Vec<i32>, h: i32) -> i32 {
  let (mut low, mut high) = (1, *piles.iter().max().unwrap());
  let mut answer = high;

  while low <= high {
    let mid = (low + high) / 2;
    let mut hours = 0;
    for &pile in piles.iter() {
      hours += (pile + mid - 1) / mid;
    }
    if hours <= h {
      answer = mid;
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  answer
}

fn main() {
  let piles = vec![3, 6, 7, 11];
  let h = 8;
  println!("{}", min_eating_speed(&piles, h));
}

Kotlin implementation

fun minEatingSpeed(piles: IntArray, h: Int): Int {
  var low = 1
  var high = piles.maxOrNull() ?: 1
  var answer = high

  while (low <= high) {
    val mid = (low + high) / 2
    var hours = 0
    for (pile in piles) {
      hours += (pile + mid - 1) / mid
    }
    if (hours <= h) {
      answer = mid
      high = mid - 1
    } else {
      low = mid + 1
    }
  }
  return answer
}

fun main() {
  val piles = intArrayOf(3, 6, 7, 11)
  val h = 8
  println(minEatingSpeed(piles, h))
}

Swift implementation

import Foundation

func minEatingSpeed(_ piles: [Int], _ h: Int) -> Int {
  var low = 1, high = piles.max()!
  var answer = high

  while low <= high {
    let mid = (low + high) / 2
    var hours = 0
    for pile in piles {
      hours += Int(ceil(Double(pile) / Double(mid)))
    }
    if hours <= h {
      answer = mid
      high = mid - 1
    } else {
      low = mid + 1
    }
  }
  return answer
}

let piles = [3, 6, 7, 11]
let h = 8
print(minEatingSpeed(piles, h))

TypeScript implementation

function minEatingSpeed(piles: number[], h: number): number {
  let low = 1;
  let high = Math.max(...piles);
  let answer = high;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    let hours = 0;
    for (const pile of piles) {
      hours += Math.ceil(pile / mid);
    }
    if (hours <= h) {
      answer = mid;
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  return answer;
}

console.log(minEatingSpeed([3, 6, 7, 11], 8));

Time complexity

CaseTimeExplanation
best caseO(n * log m)Where n = number of piles, m = max(pile). Binary search over m with O(n) check each time.
average caseO(n * log m)Performs log(m) iterations of binary search with O(n) check per iteration.
worst caseO(n * log m)In worst case, binary search runs full range from 1 to max(pile), checking all piles each time.

Space complexity

O(1)

Only a constant number of variables are used for computation. No additional memory is required.