Python 0875.py
class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
freq = defaultdict(int)
for p in piles:
freq[p] += 1
guess = max(freq)
while guess & (guess - 1): # round to next smaller power-of-two
guess &= guess - 1
step = guess // 2
# round up
def calc(k):
return sum(freq[f] * (1 + (f - 1) // k) for f in freq)
while step > 0:
hours = calc(guess)
# binary search
if hours > h:
guess += step
else:
guess -= step
step //= 2
# fine tuning
while calc(guess) > h:
guess += 1
while guess > 1 and calc(guess - 1) <= h:
guess -= 1
return guess
Difficulty
and has an acceptance rate of about 50% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “minimum eating speed” problem by determining the smallest integer speed k that allows a set of banana piles to be consumed within a given number of hours h. The algorithm builds a frequency map of pile sizes, derives an initial guess for the speed based on the highest frequency, and then refines that guess through a combination of binary-style stepping and fine-tuning loops. Throughout the process, the code leverages integer arithmetic and bitwise tricks to keep the computation efficient.
Frequency Map Construction
The first phase aggregates identical pile sizes, turning the original list into a dictionary that records how many times each distinct size appears. This reduces the amount of work needed in later calculations because each unique size is processed only once.
freq = defaultdict(int)
for p in piles:
freq[p] += 1
By collapsing duplicate values, the algorithm avoids repeatedly evaluating the same division and ceiling operations for piles of equal size.
Initial Guess Computation
The next step selects an initial speed guess based on the maximum key in the frequency map. The code then rounds this value down to the nearest power of two using a classic bit-mask technique. The resulting guess serves as a starting point for the search, while step is set to half of that power-of-two value.
guess = max(freq)
while guess & (guess - 1): # round to next smaller power-of-two
guess &= guess - 1
step = guess // 2
The bitwise loop repeatedly clears the lowest set bit until only the highest one remains, effectively extracting the greatest power of two that does not exceed the original maximum pile size. This choice of starting point ensures that the subsequent stepping process begins with a coarse granularity that quickly narrows the search space.
Hour Calculation Function
A nested helper function calc(k) computes the total number of hours required to finish all piles when eating at speed k. For each distinct pile size f, the expression 1 + (f - 1) // k yields the ceiling of f / k without using floating-point arithmetic. Multiplying by the frequency of that size accounts for all identical piles.
def calc(k):
return sum(freq[f] * (1 + (f - 1) // k) for f in freq)
This formulation handles the edge case where a pile size is exactly divisible by k as well as the case where a single extra hour is needed for the remainder. Because the function works on the compressed frequency map, its runtime scales with the number of distinct pile sizes rather than the total number of piles.
Iterative Search Loop
The core of the algorithm is a loop that adjusts guess using a decreasing step. In each iteration, the total hours for the current guess are computed. If the required hours exceed the allowed limit h, the guess is increased by step; otherwise it is decreased. After each adjustment, step is halved, mimicking a binary search but with a dynamic step size that adapts to the current region of the search space.
while step > 0:
hours = calc(guess)
# binary search
if hours > h:
guess += step
else:
guess -= step
step //= 2
This loop gracefully handles scenarios where the initial guess is far from the optimal speed. By halving step each time, the algorithm converges rapidly, and the use of integer division ensures that step eventually reaches zero without overshooting.
Fine Tuning Phase
After the coarse search finishes, two small loops perform precise adjustments. The first loop increments guess until the hour count falls within the allowed limit, covering the case where the previous step left the guess slightly too low. The second loop moves the guess downward as long as decreasing it still satisfies the hour constraint, guaranteeing that the final answer is the minimal feasible speed.
while calc(guess) > h:
guess += 1
while guess > 1 and calc(guess - 1) <= h:
guess -= 1
These loops address edge conditions such as when the optimal speed is exactly one, or when the coarse search lands on a value that is just above the true minimum. By checking guess > 1 before attempting to decrement, the code avoids stepping into non-positive speeds, which would be invalid for the problem definition.
Performance Optimizations
Several deliberate choices contribute to the efficiency of the solution. The frequency map reduces the number of division operations, especially beneficial when many piles share the same size. The bitwise rounding to a power of two provides a fast way to obtain a suitable starting magnitude for the search without resorting to logarithmic functions. The stepping loop’s halving strategy ensures logarithmic convergence while staying entirely in integer arithmetic, avoiding the overhead of floating-point calculations. Finally, the fine-tuning loops are bounded by the small range left after the main search, so they execute only a few iterations even in worst-case scenarios.
Overall, the code combines data reduction, bitwise tricks, and a disciplined search pattern to arrive at the minimal eating speed with a compact and performant implementation.
ELI5 - Simplified Explanation
Imagine a hungry little monkey who wants to eat all the bananas in different piles before the guard comes back. Some piles have many bananas and others have just a few. The monkey can decide how many bananas to eat every hour. If the monkey eats too slowly, the time will run out, but eating too fast might be unnecessary.
To find the perfect speed, this code organizes the bananas into groups to keep track of how many there are. It starts by making a clever guess about the speed. It uses a special trick to jump around sizes to get close to the right number quickly. Think of this like playing a game of hot and cold where the computer tests a speed and then changes the guess based on whether the monkey finished the bananas in time.
Once the guess gets very close to the right answer, the code stops jumping in big steps. Instead, it slowly moves the speed number up or down one by one until it finds the smallest eating speed that still allows the monkey to finish all the piles before the time limit ends. It is just like finding the exact right pace to finish a snack before it is time to go play again.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Rust | Python | C# | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| bujosa | Rust | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| bujosa | Rust | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 774: Minimize Max Distance to Gas Station
- problem 2064: Minimized Maximum of Products Distributed to Any Store
- problem 2137: Pour Water Between Buckets to Make Water Levels Equal
- problem 2226: Maximum Candies Allocated to K Children
- problem 2498: Frog Jump II
- problem 2594: Minimum Time to Repair Cars
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1456: Maximum Number of Vowels in a Substring of Given Length
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality