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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit