← Back to Algorithms, page 2

algorithms-0030 · Medium mid

Koko eating bananas: find the minimum eating speed that lets someone finish all piles within h hours, using binary search on the answer.

If speed k works, any faster speed also works, so "can finish at speed k" is a monotonic predicate over k from 1 to max(pile). Binary search for the smallest k that passes; each check sums ceil(pile / k) in O(n). Total O(n log M) where M is the largest pile, instead of trying every speed.

Full answer

Problem

There are piles of bananas. Each hour, Koko picks one pile and eats up to k bananas from it (if the pile has fewer, she finishes it and waits for the next hour). Return the minimum integer k that lets her finish within hours.

Example: piles = [3, 6, 7, 11], hours = 8 gives 4. At speed 4 the piles take 1 + 2 + 2 + 3 = 8 hours; speed 3 takes 1 + 2 + 3 + 4 = 10.

Constraints: 1 <= len(piles) <= 10^4, len(piles) <= hours <= 10^9, piles up to 10^9.

Brute force

Try k = 1, 2, 3, ... until it works: O(n x M), which is impossible for M = 10^9.

Optimal approach

  1. The answer lies in [1, max(piles)]: speed max(piles) finishes each pile in one hour, which is enough since hours >= len(piles).
  2. hours_needed(k) = sum(ceil(p / k)), computed as (p + k - 1) // k to stay in integers.
  3. Binary search: if hours_needed(mid) <= hours, then mid works and the answer is at most mid (hi = mid); otherwise lo = mid + 1.
  4. When lo == hi, that is the smallest working speed.

Why it works

hours_needed(k) never increases as k grows, so the predicate "finishes in time" is false for small k and true from some point on. Binary search finds the first true value of a monotonic predicate, exactly as lower bound finds the first index with value at least a target.

Complexity

O(n log M) time, where M = max(piles): about 30 iterations for M = 10^9, each O(n). O(1) space.

Code

python
def min_eating_speed(piles, hours):
    """Smallest integer speed k so all piles are eaten within `hours` hours.

    Binary search on the answer: feasibility is monotonic in k.
    """
    if hours < len(piles):
        raise ValueError("need at least one hour per pile")

    def hours_needed(k):
        return sum((p + k - 1) // k for p in piles)   # ceil(p / k) without floats

    lo, hi = 1, max(piles)
    while lo < hi:
        mid = (lo + hi) // 2
        if hours_needed(mid) <= hours:
            hi = mid             # mid works; maybe something smaller also works
        else:
            lo = mid + 1
    return lo


def brute(piles, hours):
    k = 1
    while sum((p + k - 1) // k for p in piles) > hours:
        k += 1
    return k


if __name__ == "__main__":
    for f in (min_eating_speed, brute):
        assert f([3, 6, 7, 11], 8) == 4
        assert f([30, 11, 23, 4, 20], 5) == 30
        assert f([30, 11, 23, 4, 20], 6) == 23
        assert f([1], 1) == 1
    assert min_eating_speed([1000000000], 2) == 500000000   # large pile: log steps only
    try:
        min_eating_speed([1, 2, 3], 2)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Save as a30_koko.py and run python3 a30_koko.py. It prints all tests passed (Python 3.13.5).

Edge cases

One pile. hours == len(piles) (answer is the largest pile). Very large piles (integer ceiling avoids float rounding errors). hours < len(piles) is impossible and raises ValueError.

Pattern

Binary search on the answer: when you cannot search the input directly but can check "is answer x feasible?" and feasibility is monotonic. Other examples: capacity to ship packages, split array largest sum, minimum days to make bouquets, integer square root.

python
def min_eating_speed(piles, hours):
    """Smallest integer speed k so all piles are eaten within `hours` hours.

    Binary search on the answer: feasibility is monotonic in k.
    """
    if hours < len(piles):
        raise ValueError("need at least one hour per pile")

    def hours_needed(k):
        return sum((p + k - 1) // k for p in piles)   # ceil(p / k) without floats

    lo, hi = 1, max(piles)
    while lo < hi:
        mid = (lo + hi) // 2
        if hours_needed(mid) <= hours:
            hi = mid             # mid works; maybe something smaller also works
        else:
            lo = mid + 1
    return lo


def brute(piles, hours):
    k = 1
    while sum((p + k - 1) // k for p in piles) > hours:
        k += 1
    return k


if __name__ == "__main__":
    for f in (min_eating_speed, brute):
        assert f([3, 6, 7, 11], 8) == 4
        assert f([30, 11, 23, 4, 20], 5) == 30
        assert f([30, 11, 23, 4, 20], 6) == 23
        assert f([1], 1) == 1
    assert min_eating_speed([1000000000], 2) == 500000000   # large pile: log steps only
    try:
        min_eating_speed([1, 2, 3], 2)
        raise AssertionError("expected ValueError")
    except ValueError:
        pass
    print("all tests passed")

Integer ceiling division in the feasibility check; a brute force over speeds is cross-checked on small inputs.

Complexity

Time: O(n log M), M = max(piles). Space: O(1). About 30 binary search steps when piles reach 10^9.

By level

Fresher: Writes the feasibility check, notices that faster speeds are always fine and applies binary search over speeds. Should explain why speed max(piles) always works.

Mid: Sets correct bounds, uses integer ceiling and explains the first-true search. Tests the case where hours equals the number of piles.

Senior: Generalises binary search on the answer, including real-valued answers with a precision stop, and identifies when the predicate is not monotonic. Can explain how to stop a real-valued version with a precision limit.

Key points

  • Feasibility is monotonic in speed
  • Search the speed range [1, max(piles)]
  • Check cost is sum of ceil(pile / k)
  • Use integer ceiling (p + k - 1) // k
  • O(n log M) total

Common mistakes

  • Trying every speed
  • Using floating-point ceil and getting rounding errors on big values
  • Wrong search bounds such as starting at 0
  • Using hi = mid - 1 when mid works and skipping the answer

Follow-ups

  • How would you solve capacity to ship packages within d days?
  • What if speeds could be real numbers?
  • How do you choose the bounds in general?

Tips

  • Say "is speed k feasible?" out loud
  • Justify monotonicity before searching
  • State the bounds and why they are safe

Evaluation rubric

  • Correct monotonic predicate and bounds
  • Correct binary search for the first feasible value
  • Correct complexity
  • Handles large values