DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 875: Koko Eating Bananas — Step-by-Step Visual Trace

Medium — Binary Search | Array | Math

The Problem

Find the minimum eating speed (bananas per hour) such that Koko can eat all banana piles within h hours, where she can only eat from one pile per hour.

Approach

Use binary search on the eating speed range from 1 to max(piles). For each candidate speed, calculate total hours needed using ceiling division, then adjust search bounds based on whether it exceeds the time limit.

Time: O(n log m) · Space: O(1)

Code

class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        left, right = 1, max(piles)

        while left < right:
            mid = left + (right - left) // 2
            hours = sum((pile + mid - 1) // mid for pile in piles)

            if hours > h:
                left = mid + 1
            else:
                right = mid

        return left
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)