↻one more pass.
Binary search · Medium

Koko Eating Bananas: the idea to remember.

Find the smallest integer eating speed that finishes all piles within h hours, with h at least the number of piles.

Solve on LeetCode ↗

The core insight

Binary search the first feasible speed. Compute required hours with ceiling division.

Why it works

If a speed is feasible, every larger speed is feasible. This monotone predicate identifies a boundary.

The mistake to avoid

Use a long accumulator: the sum of required hours can exceed an int.

Time: O(n log M), M is the largest pileSpace: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int minEatingSpeed(int[] piles, int h) {
    int left = 1, right = Arrays.stream(piles).max().orElse(1);
    while (left < right) {
        int mid = left + (right - left) / 2;
        long hours = 0;
        for (int pile : piles) hours += (pile + (long) mid - 1) / mid;
        if (hours <= h) right = mid; // mid may be the first feasible speed.
        else left = mid + 1;
    }
    return left;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.