Koko Eating Bananas
On this page
Problem statement
There are several piles of bananas and h hours before the guards return. Each hour, Koko picks one pile and eats up to k bananas from it; if the pile has fewer than k, she finishes it and waits for the next hour. Return the smallest integer speed k that lets her finish every pile within h hours. You can assume h is at least the number of piles.
The story hides a very reusable idea: binary search on the answer. You don't search an array; you search the range of possible speeds, because "fast enough" switches from false to true exactly once. Original problem: LeetCode 875.
Example

Input: piles = [3, 6, 7, 11], h = 8
Output: 4
Input: piles = [30, 11, 23, 4, 20], h = 6
Output: 23
Constraints (assumed)
- 1 ≤ number of piles ≤ 10,000; number of piles ≤ h ≤ 10⁹.
- 1 ≤ pile size ≤ 10⁹.
What this question tests
- Recognizing a monotonic yes/no question ("is speed k enough?") and binary searching it.
- Choosing correct search bounds (1 and the largest pile).
- Integer ceiling division and overflow awareness.
Questions to ask first
- Can she move to another pile within the same hour? (Here: no; leftover time in an hour is wasted. That's why it's a ceiling.)
- Is h always at least the number of piles? (Here: yes, so an answer always exists.)
- How large are piles and h? Sizes up to 10⁹ mean 64-bit sums and careful rounding.
- Integer speeds only? (Here: yes.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.