Koko Eating Bananas

Free with account Updated Nov 19, 2026 · 5 min read
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

    Piles of 3, 6, 7 and 11 bananas with 8 hours: speed 4 takes 1 + 2 + 2 + 3 = 8 hours, and speed 3 would take 10.
    Piles of 3, 6, 7 and 11 bananas with 8 hours: speed 4 takes 1 + 2 + 2 + 3 = 8 hours, and speed 3 would take 10.
    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

    1. 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.)
    2. Is h always at least the number of piles? (Here: yes, so an answer always exists.)
    3. How large are piles and h? Sizes up to 10⁹ mean 64-bit sums and careful rounding.
    4. Integer speeds only? (Here: yes.)