MEDIUM NC#30 Binary Search
875. Koko Eating Bananas
๐ Problem
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. Return the minimum integer k such that she can eat all the bananas within h hours.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขMidpoint overflow-safe math
- โขLoop invariants
- โขMonotonic condition design
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Binary Search reasoning pattern
- โขApply Backtracking reasoning pattern
๐ก Approach
- โ Use binary search to find minimum eating speed k
- โ Lower bound: 1, Upper bound: max(piles)
- โ For each k, calculate hours needed: sum(ceil(pile/k))
- โ If hours <= h, try smaller k; else try larger k
- โ Time: O(n * log(max(piles))), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse binary search to find minimum eating speed k
- โขLower bound: 1, Upper bound: max(piles)
- โขFor each k, calculate hours needed: sum(ceil(pile/k))
Common Pitfalls
- โขIf hours <= h, try smaller k; else try larger k
- โขTime: O(n * log(max(piles))), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
minEatingSpeed([3,6,7,11], 8); Expected:
4 Test Case 2
Not run Input:
minEatingSpeed([30,11,23,4,20], 5); Expected:
30 Test Case 3
Not run Input:
minEatingSpeed([30,11,23,4,20], 6); Expected:
23 ๐ Code Editor
๐ค Output