The Problem

Koko loves eating 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 eating speed k (bananas per hour). Each hour, she picks a pile and eats k bananas from it. If a pile has fewer than k bananas, she eats all of them and won't eat any more that hour.

Return the minimum integer k such that she can eat all the bananas within h hours.

Interactive Visualization

Speed:
Banana Piles
Binary Search Range
lo
1
mid (k)
β€”
hi
11
Current Step
Press Step or Play to begin.
Code
import kotlin.math.ceilfun minEatingSpeed(piles: IntArray, h: Int): Int {    var lo = 1    var hi = piles.max()    while (lo < hi) {        val mid = (lo + hi) / 2        val hours = piles.sumOf { ceil(it.toDouble() / mid).toInt() }        if (hours <= h) {  // can finish -> try smaller            hi = mid        } else {           // too slow -> need faster            lo = mid + 1        }    }    return lo  // minimum valid speed}

How It Works

Key Insight

The eating speed k has a monotonic property: if Koko can finish at speed k, she can also finish at any speed greater than k. This makes it a perfect candidate for binary search on the answer.

The Algorithm

  • Search space: lo = 1 (minimum possible speed), hi = max(piles) (eating the largest pile in one hour β€” never need more)
  • Each iteration: try the middle speed mid = (lo + hi) // 2
  • Check feasibility: calculate total hours needed at speed mid β†’ for each pile, it takes ⌈pile / midβŒ‰ hours
  • If feasible (total hours ≀ h): we might be able to go slower β†’ hi = mid
  • If not feasible: we need to eat faster β†’ lo = mid + 1
  • When lo = hi: we've found the minimum valid speed

Complexity

Time O(n Β· log(max(piles)))
Space O(1)

We do log(max(piles)) binary search iterations, and each iteration scans all n piles to compute the total hours.