Algo-Sim › Binary Search
Koko Eating Bananas
Medium · Binary Search · step through it in Java, Python and C++ on your own input
Find the slowest eating speed that finishes every pile within h hours. Binary search on the answer.
Problem
There are piles[i] bananas in pile i, and the guards return in h hours. Each hour Koko picks one pile and eats k bananas from it; if the pile has fewer than k, she eats all of it and waits out the hour. Return the smallest integer k that lets her eat every banana within h hours.
Constraints
- 1 ≤ piles.length ≤ 10⁴
- piles.length ≤ h ≤ 10⁹
- 1 ≤ piles[i] ≤ 10⁹
- A pile of p bananas takes ⌈p / k⌉ hours
Edge cases to test
- h equals the number of piles: speed = max pile
- One huge pile
- h very large: speed 1
Follow-up questions
- How do you count hours without floating point?
(pile + speed − 1) / speedis the ceiling of the division in integers.- What makes a problem "binary search on the answer"?
- A yes/no check that is monotonic in the answer (faster always finishes if slower does). Search the smallest yes: O(n log max).
Solution
Java
public int minEatingSpeed(int[] piles, int h) {
int lo = 1, hi = Arrays.stream(piles).max().getAsInt(), ans = hi;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (hoursAt(piles, mid) <= h) {
ans = mid; hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private long hoursAt(int[] piles, int speed) {
long hours = 0;
for (int p : piles) hours += (p + speed - 1) / speed;
return hours;
}Python
def min_eating_speed(piles, h):
lo, hi = 1, max(piles)
ans = hi
while lo <= hi:
mid = lo + (hi - lo) // 2
if hours_at(piles, mid) <= h:
ans, hi = mid, mid - 1
else:
lo = mid + 1
return ans
def hours_at(piles, speed):
hours = 0
for p in piles:
hours += (p + speed - 1) // speed
return hoursC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minEatingSpeed(vector<int> &piles, int h) {
int lo = 1, hi = *max_element(piles.begin(), piles.end()), ans = hi;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (hoursAt(piles, mid) <= h) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
long long hoursAt(vector<int> &piles, int speed) {
long long hours = 0;
for (int p : piles)
hours += (p + speed - 1) / speed;
return hours;
}
};
More Binary Search problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)