Data Structures & Algorithms Binary Search
💡
Exercise 53

Koko Eating Bananas 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Koko loves bananas. There are n piles of bananas. She can eat at speed k bananas per hour. Each hour she picks one pile and eats k bananas from it (or finishes it if fewer remain).

She has h hours to eat all bananas. Find the minimum speed k such that she can finish within h hours.

piles = [3,6,7,11], h = 8 → 4 # At speed 4: ceil(3/4)=1, ceil(6/4)=2, ceil(7/4)=2, ceil(11/4)=3 # Total = 1+2+2+3 = 8 hours ✓

This is binary search on the answer! Search space: k from 1 to max(piles). For each k, calculate total hours. If ≤ h, try smaller k.

📋 Instructions
Implement `min_eating_speed(piles, h)` using binary search on the answer. Test with `piles = [3,6,7,11]`, `h = 8`. Print the result.
Binary search: left=1, right=max(piles). For each mid speed, compute total hours using math.ceil(pile/mid) for each pile. If total <= h, try smaller (right=mid). Else try bigger (left=mid+1).
🧪 Test Cases
Input
min_eating_speed([3,6,7,11], 8)
Expected
4
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.