Prepin
Log in

M

Koko is consuming bananas.

Approach / Explanation

The problem known as Koko eating bananas typically pertains to a famous algorithmic challenge involving a monkey named Koko who consumes bananas. Each hour, Koko selects a pile of bananas and eats from that pile until the hour concludes. This problem generally focuses on Koko's goal to either maximize or minimize a certain aspect (such as the total number of bananas eaten or the time spent) while adhering to specific limitations regarding the size of the banana piles and Koko's eating speed. To fully understand the problem, you should: Comprehend the constraints related to the banana piles and Koko's eating rate. Identify the quantity that Koko needs to maximize or minimize. Establish the appropriate strategy for Koko to achieve the desired maximization or minimization of that quantity.

Suggested Answer

In an example where Koko aims to minimize the time required to finish all the bananas, and the piles vary in size, you can determine the maximum size among the piles (let's denote it as maxSize ). Next, perform a binary search ranging from 1 to maxSize to find the minimum time needed for Koko to consume the bananas. For each time calculation, you compute the total time for all piles using the formula (pile[i] - 1) / mid + 1. If the resulting time exceeds H , continue the binary search; otherwise, terminate the search. Thus, the pseudo code is as follows: function minEatingSpeed(piles, H) { let left = 1, right = Math.max(...piles) while(left < right) { let mid = left + (right - left) / 2 if(piles.reduce((a, b) => a + Math.ceil(b / mid), 0) > H) { left = mid + 1 } else { right = mid } } return left }

Alternative Answer

In a different situation where Koko is allowed to eat bananas at most K times, he always selects the largest banana pile and consumes K bananas. If there are fewer than K bananas in that pile, Koko will eat all of them and will not consume any more bananas for that hour. In this scenario, the Heap data structure can be utilized to manage the banana piles. Each time, the largest pile is removed, Koko eats K bananas, and if any bananas remain, the updated pile is pushed back into the Heap. Here is a solution in Python: import heapq class Solution ( object ) : def minEatingSpeed ( self , piles , H ) : piles = [ - pile for pile in piles ] heapq . heapify ( piles ) time = 0 while time < H : # Choose the pile with the most bananas pile = - heapq . heappop ( piles ) time += math . ceil ( pile / K ) if pile > K : # Return remaining bananas of current pile to the heap heapq . heappush ( piles , - ( pile - K ) ) return time

Question Details

Difficulty & Category

Medium
algorithms

Companies

Amazon
Microsoft

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.