A-030● Day 302026.06.05mediumleetcode #875neetcode150
Koko Eating Bananas
#array#binary-search
01
Problem
· problemKoko 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. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return the minimum integer k such that she can eat all the bananas within h hours.
constraints
- · 1 ≤ piles.length ≤ 10⁴
- · piles.length ≤ h ≤ 10⁹
- · 1 ≤ piles[i] ≤ 10⁹
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐Can Koko eat from multiple piles in a single hour?
- ☐Can Koko's eating speed k change over time?
- ☐Must the eating speed k be an integer?
- ☐Does the order of eating piles matter?
- ☐If k < max(piles), is it impossible to finish all bananas?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize binary search bounds
○
l, r = 1, max(piles)
○
l, r = 0, sum(piles)
○
l, r = 1, len(piles)
step 2· Initialize result with maximum speed
○
res = r
○
res = l
○
res = -1
step 3· Continue while search space exists
○
while l <= r:
○
while l < r:
○
while l <= r - 1:
step 4· Calculate candidate eating speed│ nested
○
k = (l + r) // 2
○
k = (l + r) / 2
○
k = r - (r - l) // 2
step 5· Calculate total hours needed for speed k│ │ nested
○
totalTime += math.ceil(float(p) / k)
○
totalTime += p // k
○
totalTime += p / k
step 6· Update right bound when feasible│ │ nested
○
r = k - 1
○
l = k + 1
○
r = k
step 7· Update left bound when infeasible│ │ nested
○
l = k + 1
○
r = k - 1
○
l = k
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[3,6,7,11] 8→
4
case 2
[30,11,23,4,20] 5→
30
case 3
[30,11,23,4,20] 6→
23
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.