Logo for ammarahmed.ca
Medium
Dec 22, 2025
#binary-search
#math

875. Koko Eating Bananas

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

Return the minimum integer k such that she can eat all the bananas within h hours.

Example 1:

1Input: piles = [3,6,7,11], h = 8 2Output: 4

Example 2:

1Input: piles = [30,11,23,4,20], h = 5 2Output: 30

Example 3:

1Input: piles = [30,11,23,4,20], h = 6 2Output: 23
  • 1 <= piles.length <= 104
    • piles.length <= h <= 109
      • 1 <= piles[i] <= 109

        Constraints:

        Notes

        Intuition

        The eating speed ranges from 1 to max(piles). Binary search finds the minimum speed that lets Koko finish in time. Higher speeds always work if lower speeds work, so we're finding a threshold.

        Implementation

        Binary search on speed from 1 to max(piles). For each candidate speed, calculate total hours needed (sum of ceil(pile/speed) for each pile). If hours exceed h, we need more speed—search right. Otherwise, search left for potentially slower valid speeds. When the loop exits, l is the minimum valid speed.

        Edge-cases

        Use ceiling division because even one banana in a pile takes a full hour. The answer is l at the end, not r.

        • Time: O(n log m) — where m is max(piles), binary search with O(n) validation
          • Space: O(1) — only tracking pointers

            Complexity

            Solution

            1from typing import List 2import math 3 4class Solution: 5 def minEatingSpeed(self, piles: List[int], h: int) -> int: 6 l, r = 1, max(piles) 7 8 while l <= r: 9 speed = (l + r) // 2 10 # calculating hours for this speed 11 hours = 0 12 for pile in piles: 13 hours += math.ceil(pile/speed) 14 15 if hours > h: # increase speed 16 l = speed + 1 17 else: # decrease speed 18 r = speed - 1 19 20 return l 21 22 23 24 25if __name__ == "__main__": 26 # Include one-off tests here or debugging logic that can be run by running this file 27 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 28 solution = Solution() 29