Koko Eating Bananas

Medium

Topics
ArrayBinary Search

Koko has piles of bananas (nums) and h hours (passed as target) before the guards return. Each hour she eats up to k bananas from one pile. Return the minimum integer speed k so she finishes all piles within h hours.

Example 1

306172113
What is being searched is not a position in the array — it is the answer itself, the eating speed.
Cells are the array values; the small numbers underneath are indices.
Input:  piles = [3,6,7,11], h = 8
Output: 4

Example 2

30011123243204
Input:  piles = [30,11,23,4,20], h = 5
Output: 30

Constraints

  • 1 <= piles.length <= 10^4
  • piles.length <= h <= 10^9
  • 1 <= piles[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

"Can Koko finish at speed k?" is monotonic: if a speed works, every larger speed works too. That monotonic yes/no boundary is exactly what binary search finds.

So binary-search the speed in [1, max(piles)] for the smallest feasible value.

Approach

  1. At speed k, hours needed = sum(ceil(pile / k)).
  2. Binary-search k: if the hours are within h, try slower (smaller k); otherwise faster.
  3. Return the smallest feasible speed.

Walkthrough

piles=[3,6,7,11], h=8
k=4 -> ceil: 1+2+2+3 = 8 <= 8 feasible
k=3 -> 1+2+3+4 = 10 > 8 not feasible
smallest feasible = 4

Complexity

  • Time — O(n log maxPile): each binary-search step scans the piles once.
  • Space — O(1): a few scalars.

Common Pitfalls

  • Search the answer space (speeds), not the array itself.
  • mid = (lo + hi) / 2 is the textbook form, and in Java or C++ it is the one that bites: the moment lo + hi passes 2^31 - 1 it wraps negative and the index flies out of range. This problem’s bounds never get close, so the code above is correct as written, but lo + (hi - lo) / 2 is the habit worth keeping — same answer, same cost, no overflow. Python’s integers are arbitrary precision, so it is a non-issue there.

Full Solution — all languages

class Solution:
    def minEatingSpeed(self, nums, target):
        lo, hi = 1, max(nums)
        while lo < hi:
            mid = (lo + hi) // 2
            hours = sum((x + mid - 1) // mid for x in nums)
            if hours <= target:
                hi = mid
            else:
                lo = mid + 1
        return lo
SensAI
Beta
Tap the mic to stop voice mode