InterviewPrepKit

Home / Coding / Binary Search

Koko Eating Bananas

medium Original β†—
Solving tips
  • This is binary search on the answer: feasibility is monotone in speed k, so search the speed axis [1, max(piles)] for the first feasible k.
  • The feasibility check is total hours = sum of ceil(p / k); compute ceil with integer math like (p + k - 1)//k or -(-p//k) to stay exact.
  • Bound hi at max(piles) (speeds above it change nothing) and use the first-True convention: hours <= h means hi = mid, else lo = mid+1.
  • O(n log m) time where m = max(piles), O(1) space; pile eating order is irrelevant since the total is just a sum of ceilings.

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. You’re guaranteed h >= n, so a solution always 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 β€” per-candidate checking must be paired with something 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, can she finish at speed k+1? So the answers to "can she finish at speed k?" for k = 1, 2, 3, … look like No, No, …, No, Yes, Yes, … What are you really searching for?
Hint 3 Binary search k over [1, max(piles)]. For each mid, compute total hours = sum of ceil(p / mid); if it's within h, try slower (`hi = mid`), else go faster (`lo = mid + 1`). The convergence point is the minimum feasible speed.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.