#875

Koko Eating Bananas

Medium Binary search on the answer

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Koko eats from one pile per hour at speed k bananas/hour (a smaller pile still takes the full hour). Find the minimum k that lets her finish all piles within h hours.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the slowest eating speed that still finishes all piles in h hours.

Why this works: faster always works if slower works, so binary search the speed and count hours = sum of ceil(pile / speed).

Example: piles [3, 6, 7, 11], h = 8

speed 4: 1+2+2+3 = 8 ✓speed 3: 1+2+3+4 = 10 ✗answer 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Summing hours in int — with many piles and k = 1 it can overflow. Use long.

Solve on LeetCode ↗
Complexity
  • Time: O(n log M), M = largest pile.
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon