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
- The answer lies in
[1, max(piles)]: speedmax(piles)finishes each pile in one hour, which is enough sincehours >= len(piles). hours_needed(k) = sum(ceil(p / k)), computed as(p + k - 1) // kto stay in integers.- Binary search: if
hours_needed(mid) <= hours, thenmidworks and the answer is at mostmid(hi = mid); otherwiselo = mid + 1. - 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
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.
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