Koko Eating Bananas — LeetCode 875 Python Solution

MediumArrayBinary Search
Problem
#875
Reading time
2 min

The problem

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas.

Example

Input
piles = [3,6,7,11], h = 8
Output
4

Python solution

Python
class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        def check(k: int) -> bool:
            return sum((x + k - 1) // k for x in piles) <= h

        return 1 + bisect_left(range(1, max(piles) + 1), True, key=check)

Complexity

MeasureComplexity
TimeO(n \times \log M), where n and M are the length and maximum value of the array `piles` respectively
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 875. Koko Eating Bananas is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and LeetCode 75.

Frequently asked questions

How hard is LeetCode 875. Koko Eating Bananas?
LeetCode 875. Koko Eating Bananas is rated Medium on LeetCode.
What is the time complexity of LeetCode 875. Koko Eating Bananas?
The Python solution on this page runs in O(n \times \log M), where n and M are the length and maximum value of the array `piles` respectively.
What is the space complexity of LeetCode 875. Koko Eating Bananas?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 875. Koko Eating Bananas cover?
LeetCode 875. Koko Eating Bananas is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview