Taro Logo

Koko Eating Bananas

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+28
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.2K views
Topics:
ArraysBinary Search

Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.

Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.

Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.

Return the minimum integer k such that she can eat all the bananas within h hours.

Example 1:

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

Example 2:

Input: piles = [30,11,23,4,20], h = 5
Output: 30

Example 3:

Input: piles = [30,11,23,4,20], h = 6
Output: 23

Constraints:

  • 1 <= piles.length <= 104
  • piles.length <= h <= 109
  • 1 <= piles[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the values within the `piles` array and the total hours `h`?
  2. Is it guaranteed that the total number of hours `h` will always be greater than or equal to the number of piles?
  3. Can the `piles` array contain empty inputs or zero bananas in any pile?
  4. Since multiple eating speeds could potentially satisfy the hour limit, am I always expected to return the minimum integer speed $k$?
  5. What should be returned if `h` is less than the number of piles, or is that input combination guaranteed not to occur?

Brute Force Solution

Approach

Imagine you need to figure out the slowest speed at which someone can eat all their piles of food within a given time limit. The brute force approach involves testing every single possible eating speed one by one, starting from the absolute slowest possible speed and working your way up.

Here's how the algorithm would work step-by-step:

  1. Begin by testing the slowest possible speed of eating just one item per hour.
  2. Calculate how long it would take to finish all the piles of food at this current testing speed.
  3. Check if the total time calculated is within the allowed deadline.
  4. If the time taken is too long and misses the deadline, throw away this speed and move up to the next slightly faster speed.
  5. Repeat the process of testing and checking each increasingly faster speed.
  6. Stop as soon as you find the very first speed that successfully finishes all the food within the deadline.
  7. Declare this winning speed as your final answer since you started from the slowest and worked your way up.

Code Implementation

import math

def min_eating_speed(piles, allowed_hours):
    # We test every possible speed starting from one because it is the slowest possible rate
    current_speed = 1
    
    while True:
        total_hours_needed = 0
        for banana_pile in piles:
            total_hours_needed += math.ceil(banana_pile / current_speed)
        
        # We stop as soon as we find the first speed that finishes all food within the deadline
        if total_hours_needed <= allowed_hours:
            return current_speed
            
        current_speed += 1

Big(O) Analysis

Time Complexity
O(max(P) * N) – In this brute force approach, the input size N represents the number of piles, and max(P) represents the maximum number of bananas in a single pile, which dictates the maximum possible eating speed we might have to test. We iterate through every possible eating speed starting from 1 up to max(P). For each speed tested, we iterate through all N piles to calculate the total hours required. Multiplying the number of tested speeds by the cost of scanning all piles yields approximately max(P) * N operations, which simplifies to O(max(P) * N).
Space Complexity
O(1) – To determine the slowest eating speed, the algorithm only allocates a few primitive variables to keep track of the current speed range boundaries and calculation results. Since no extra data structures, dynamic lists, or recursive stack frames are created, the auxiliary memory usage remains completely constant regardless of the number of piles or the size of the input.

Optimal Solution

Approach

Instead of testing every possible eating speed one by one, we can treat this like a guessing game using a range of numbers. By smartly narrowing down our guesses between the slowest and fastest possible speeds, we can quickly find the exact minimum speed needed to finish in time.

Here's how the algorithm would work step-by-step:

  1. Determine the slowest possible speed you could eat, which is one banana per hour, and the fastest possible speed, which is eating the largest pile in a single hour.
  2. Imagine a number line stretching from that slowest speed up to the fastest speed.
  3. Look at the speed right in the middle of this range and calculate how many total hours it would take to finish all the piles at this speed.
  4. Check if that middle speed allows you to finish everything within the allowed time limit.
  5. If you finished with time to spare, it means you can potentially go even slower, so completely throw away all the speeds faster than your current guess and focus only on the slower half.
  6. If you ran out of time, it means your speed was too slow, so completely throw away all the speeds slower than your current guess and focus only on the faster half.
  7. Repeat this process of halving your range until your lower and upper limits meet at a single number, which will be your answer.

Code Implementation

import math


def min_eating_speed(banana_piles, max_allowed_hours):
    lowest_possible_speed = 1
    highest_possible_speed = max(banana_piles)
    optimal_eating_speed = highest_possible_speed

    # Binary search bounds the search space to find the minimum valid speed efficiently.
    while lowest_possible_speed <= highest_possible_speed:
        current_test_speed = (lowest_possible_speed + highest_possible_speed) // 2
        hours_required = 0

        for pile in banana_piles:
            hours_required += math.ceil(pile / current_test_speed)

        # If the speed allows finishing in time, record it and try to find an even slower speed.
        if hours_required <= max_allowed_hours:
            optimal_eating_speed = current_test_speed
            highest_possible_speed = current_test_speed - 1

        # If it takes too long, discard this speed and all slower speeds since they are invalid.
        else:
            lowest_possible_speed = current_test_speed + 1

    return optimal_eating_speed

Big(O) Analysis

Time Complexity
O(n log m) – The input size is defined by n, which is the number of banana piles, and m, which is the maximum number of bananas in a single pile representing the search space for the eating speed. We perform a binary search that cuts the range of possible speeds m in half with each step, taking log m iterations. Inside each step of this binary search, we iterate through all n piles to calculate the total hours required at the current speed. Multiplying the log m binary search steps by the n operations per check yields approximately n * log m operations, which simplifies to O(n log m).
Space Complexity
O(1) – The algorithm only uses a few primitive variables like lower bound, upper bound, middle speed, and a counter to track hours. No auxiliary data structures, temporary lists, or recursive call stacks are created during the binary search process. The memory footprint remains entirely constant regardless of how many piles of bananas exist or how large those piles are. Therefore, the extra auxiliary space complexity simplifies to Big O of 1.

Edge Cases

Hours available h equals the number of piles
How to Handle:
Binary search naturally sets speed k to the maximum pile size since Koko must eat each pile in one hour.
Hours available h is extremely large relative to the number of piles
How to Handle:
Binary search efficiently shrinks the lower bound to a speed of 1 banana per hour.
Array contains a single pile with h equal to 1
How to Handle:
The algorithm correctly returns the exact size of that single pile as the minimum speed.
Array contains extremely large pile values up to 10 to the 9th power
How to Handle:
Using 64-bit integers for the upper bound of the binary search prevents any potential overflow during calculation.
All piles have identical values
How to Handle:
The ceiling division correctly aggregates the total hours required across all identical piles to determine valid speeds.
Pile values are heavily skewed with one massive pile and many tiny ones
How to Handle:
The binary search range adapts instantly to the maximum pile value ensuring the upper bound covers the worst-case pile.
0/75 completed