Koko Eating Bananas

Medium Binary Search

Problem

Koko has piles of bananas. Each hour she picks one pile and eats up to k bananas from it (whole pile if it has fewer than k). Given the piles array and an hour budget h, return the smallest integer k that lets her finish before the guards return.

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

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def minEatingSpeed(self, piles, h):
        import math
        lo, hi = 1, max(piles)
        while lo < hi:
            mid = (lo + hi) // 2
            if sum(math.ceil(p / mid) for p in piles) <= h:
                hi = mid
            else:
                lo = mid + 1
        return lo

Java

class Solution {
    public int minEatingSpeed(int[] piles, int h) {
        int left = 1, right = 1;
        for (int pile : piles) {
            right = Math.max(right, pile);
        }

        while (left < right) {
            int middle = (left + right) / 2;
            int hourSpent = 0;

            for (int pile : piles) {
                hourSpent += Math.ceil((double) pile / middle);
            }

            if (hourSpent <= h) {
                right = middle;
            } else {
                left = middle + 1;
            }
        }
        return right;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Koko Eating Bananas interactively → ← All solutions