On this page
Binary Search on Answer: Example
Koko Eating Bananas
The example is on LeetCode
Koko loves to eat bananas. There are $n$ piles of bananas, the $i^{th}$ 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.
Example
- Input: $piles = [3,6,7,11]$, $h = 8$
- Output: $4$
Solution Implementation
The Feasibility Check
Implements the predicate.
Explanation:
- Loops over each pile of bananas $(p)$.
- Computes $ceil(p / k)$ by $(p + (k – 1)) / k$.
- Accumulates total $hours$.
- If at any point $hours > h$, returns $false$ immediately (speed $k$ is too slow).
- Otherwise, returns $true$ (speed $k$ lets Koko finish in time).
Binary-Search on the Answer
Binary-Search on the Answer (Alternative Approach)
Explanation:
- Initialization
- $l = 1$ (minimum possible speed).
- $r = max(piles)$ (at worst, eat the largest pile in one hour).
- Loop Condition
- While $l < r$, we haven’t narrowed down to a single speed.
- Midpoint & Decision
- $mid = l + (r–l)/2$ picks the candidate speed.
- Call $canFinish(piles, h, mid)$:
- $true \to$ Koko can finish at speed $mid$, so the optimal speed is $\leq mid$. We set $r = mid$.
- $false \to$ too slow, so we set $l = mid + 1$.
- Termination
- The loop ends when $l == r$, which is the minimum speed at which $canFinish$ flips from $false$ to $true$.
- Return $r$.
Complexities
Time Complexity
- Each binary‐search iteration does one $canFinish$ check in $O(n)$ ($n$ = number of piles).
- Number of iterations $\approx \log_2 {(max(pile) - 1)} = O(\log M)$, where $M$ = size of largest pile.
- Total: $O(n \cdot \log M)$.
Space Complexity
$O(1)$ extra memory (ignoring input storage).
Code on GitHub
Last updated 11 May 2025, 19:46 +0500 .