InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Binary Search

Koko Eating Bananas

medium Original ↗ 00:00

Problem

Koko has n piles of bananas; pile i holds piles[i] bananas. The guards return in h hours. Koko picks a fixed eating speed k (bananas per hour). Each hour she chooses one pile and eats k bananas from it — if the pile has fewer than k left, she finishes the pile and eats nothing more that hour (she never switches piles mid-hour).

Return the minimum integer speed k that lets her finish every pile within h hours. The constraint h >= n guarantees a solution exists.

Examples

  • Input: piles = [3, 6, 7, 11], h = 8 → Output: 4 (At k=4 the piles take ⌈3/4⌉+⌈6/4⌉+⌈7/4⌉+⌈11/4⌉ = 1+2+2+3 = 8 hours — exactly in time; k=3 would need 10.)
  • Input: piles = [30, 11, 23, 4, 20], h = 5 → Output: 30 (Five piles, five hours: one pile per hour, so k must cover the biggest pile.)
  • Input: piles = [30, 11, 23, 4, 20], h = 6 → Output: 23 (One spare hour lets her split the 30-pile into two sittings; every other pile still fits in one hour at k=23.)

Constraints

  • 1 <= piles.length <= 10^4
  • piles.length <= h <= 10^9
  • 1 <= piles[i] <= 10^9
  • Pile sizes up to 10^9 mean candidate speeds range into the billions, so checking every speed one by one is too slow; the search over speeds must be logarithmic.

Think about it first

Hint 1 For a fixed speed k, how many hours does one pile of size p take? (She can't carry leftover hour-time between piles — think ceiling.) Can you compute the total hours for any k in one pass?
Hint 2 If Koko can finish at speed k, she can also finish at speed k+1. So the answers to "can she finish at speed k?" for k = 1, 2, 3, … form a run of No followed by a run of Yes. What are you searching for in that sequence?
Hint 3 Binary search k over [1, max(piles)]. For each mid, compute total hours = sum of ceil(p / mid); if it is within h, try a slower speed (`hi = mid`), else a faster one (`lo = mid + 1`). The convergence point is the minimum feasible speed.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug