Question bankPricingSign in

Koko Eating Bananas

Binary SearchMedium1:30

Koko loves eating bananas. There are n piles of bananas, where piles[i] is the number of bananas in the ith pile. Koko can eat at most k bananas per hour. Each hour, she chooses a pile and eats k bananas from it. If the pile has fewer than k bananas, she eats all of them and does not eat any more that hour. Koko has h hours to eat all the bananas. Find the minimum integer k (eating speed) such that she can finish all bananas within h hours.

For example, given piles = [3, 6, 7, 11] and h = 8, the output is 4 because at speed 4: pile 3 takes 1 hour, pile 6 takes 2 hours, pile 7 takes 2 hours, pile 11 takes 3 hours, total = 8 hours.

Explain how this is a binary search problem, what you are searching over, and analyze complexity.

How to approach it

  • Hint 1

    You are not searching through the piles -- you are searching for the right eating speed k.

  • Hint 2

    The minimum possible speed is 1, the maximum is the largest pile. Binary search this range.

  • Hint 3

    For a given speed k, you can calculate total hours needed: sum of ceil(pile / k) for each pile. If total <= h, the speed is fast enough.

Ready to answer it out loud?

Record your answer in 1:30 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.

Practising needs an invite code. Join the waitlist and we’ll send you one.