AlgoInsight

DSA problem

Koko Eating Bananas

MediumBinary SearchPattern: Binary Searchtop150GoogleFacebookAmazonMicrosoft

Koko loves to eat bananas. There are n piles of bananas, the i-th pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour. Return the minimum integer k such that she can eat all the bananas within h hours.

This is a foundational "binary search the answer" problem. Direct simulation over candidate speeds is too slow (max(piles) can be up to 10^9), but the predicate canFinish(k) — "can Koko eat everything within h hours at speed k?" — is monotonic: if speed k works, every larger k also works. So the valid speeds form a contiguous suffix [k*, ∞) and binary searching for k* is well-defined.

The predicate is simple: for speed k, the i-th pile takes ceil(piles[i] / k) hours. Sum that over all piles and check whether it is at most h. The search range for k is [1, max(piles)] — the lower bound is 1 because k must be positive, the upper bound is max(piles) because at that speed every pile is finished in one hour, costing exactly n hours which is <= h by the constraint h >= n.

Use the lower-bound shape: lo = 1, hi = max(piles), while lo < hi set hi = mid if canFinish(mid) else lo = mid + 1. The result is the smallest feasible speed. The total work is O(n log M) where M = max(piles). Watch overflow: ceil(piles[i] / k) summed over many piles can exceed 32-bit when h is large; use long in Java/C++.

Examples

Example 1
Input: piles = [3,6,7,11], h = 8
Output: 4
Explanation: At speed 4: pile 3 takes 1 h, pile 6 takes 2 h, pile 7 takes 2 h, pile 11 takes 3 h. Total 8 hours = h, so 4 works. Speed 3 needs 9 hours, so 4 is minimal.
Example 2
Input: piles = [30,11,23,4,20], h = 5
Output: 30
Explanation: There are five piles and only five hours, so Koko must clear each pile in one hour. The largest pile is 30, so the answer is 30.
Example 3
Input: piles = [30,11,23,4,20], h = 6
Output: 23
Explanation: With one extra hour, one pile can take 2 hours; at speed 23 the 30-banana pile takes 2 hours and the rest each take 1 hour for total 6.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searcharraybinary-search-the-answer

Browse all DSA problems