Skip to content
GKgkml.dev
← Problem set
#875MediumBinary search

Koko Eating Bananas

The tell: 'Minimum rate such that the job finishes in time' — a monotone feasibility question.

How you get there

  1. 1Feasibility is monotone: if speed k works, every speed above k works too.
  2. 2So binary search the answer space from 1 to max(piles), not the array.
  3. 3The predicate is a linear pass summing ceil(pile / k) hours.

Solution

Python
import math

def min_eating_speed(piles: list[int], h: int) -> int:
    def hours(k: int) -> int:
        return sum(math.ceil(p / k) for p in piles)

    lo, hi = 1, max(piles)
    while lo < hi:
        mid = (lo + hi) // 2
        if hours(mid) <= h:
            hi = mid          # mid works, try slower
        else:
            lo = mid + 1
    return lo
Time
O(n log max(piles))
Space
O(1)

What goes wrong

Starting lo at 0 divides by zero; the slowest meaningful rate is 1.