Problem 875

Abstract / Summary

Koko must eat all bananas in the minimum time by choosing how many she eats per hour, given each pile's size.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
33 lines | 843 bytes | submitted September 12, 2023 | GitHub   17% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 5 | μ = 5.15 | σ = 1.78

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
37 links | 22 authors | 9 languages

Videos

10 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

6 similar problems

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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