</>

875. Koko Eating Bananas

Medium NeetCode 150
Binary Search Time O(n log m) Space O(1)
↗ Open on LeetCode Source: Standard solution only

Quick review

Pattern
Binary Search
Time
O(n log m)
Space
O(1)

Standard Solution (C++)

SummaryKoko must finish all banana piles within a given number of hours; each hour she eats up to a chosen rate from a single pile. Find the smallest eating rate that lets her finish in time.

Approach

Binary search on the answer (the eating speed).

  • The feasible speeds range from 1 to the largest pile.
  • For a candidate speed, the hours needed is the sum over piles of ceil(pile / speed).
  • Search for the smallest speed whose required hours do not exceed the limit.
class Solution {
public:
    int minEatingSpeed(vector<int>& piles, int h) {
        int lo = 1, hi = *max_element(piles.begin(), piles.end());
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            long long hours = 0;
            for (int p : piles) hours += (p + mid - 1) / mid;
            if (hours <= h) hi = mid;
            else lo = mid + 1;
        }
        return lo;
    }
};
Time O(n log m) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern