Koko Eating Bananas

Find the minimum eating speed to finish all bananas in h hours.

Pattern

Binary Search on Answer

This problem follows the Binary Search on Answer pattern, commonly found in the Binary Search category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Binary search on speed. For each speed, check if total hours <= h.

Key Insight

Binary search on the answer space, not the data — the monotonic property is: if speed k works, any speed > k also works.

Step-by-step

  1. 1Binary search on the eating speed (1 to max pile size)
  2. 2For each candidate speed, calculate total hours needed
  3. 3Hours for each pile = ceil(pile / speed)
  4. 4If total hours <= h, try a slower speed (right = mid)
  5. 5Otherwise, speed up (left = mid + 1)

Pseudocode

left, right = 1, max(piles)
while left < right:
    mid = (left + right) // 2
    hours = sum(ceil(p / mid) for p in piles)
    if hours <= h:
        right = mid
    else:
        left = mid + 1
return left
Complexity Analysis

Time Complexity

O(n log m)

Space Complexity

O(1)
More Binary Search Problems

Master this pattern with YeetCode

Practice Koko Eating Bananas and similar Binary Search problems with flashcards. Build pattern recognition through active recall.

Practice this problem