875. Koko Eating Bananas - Detailed Explanation

Problem statement

Koko loves eating bananas. There are n piles of bananas, where the i-th pile has piles[i] bananas. The guards have gone for h hours, and Koko can decide her eating speed k (bananas per hour). Each hour, she chooses a pile and eats up to k bananas from that pile. If she finishes a pile, she moves to the next one.

Koko wants to eat all the bananas within h hours. Find the minimum integer k such that she can finish all the bananas in time.

Examples

Example 1

Input:

piles = [3, 6, 7, 11] h = 8

Output:

4

Explanation: If Koko eats at a rate of 4 bananas per hour, she will finish all the piles in exactly 8 hours.

Example 2

Input:

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

Output:

30

Explanation: She must eat at a rate of 30 bananas per hour to finish all the bananas in 5 hours.

Example 3

Input:

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

Output:

23

Explanation: With 6 hours available, Koko can eat at a rate of 23 bananas per hour and finish all piles in time.

Constraints

  • 1 <= piles.length <= 10^4
  • 1 <= piles[i] <= 10^9
  • piles.length <= h <= 10^9

Hints to solve the problem

  1. Brute force approach: Try all possible eating speeds from 1 up to the size of the largest pile. Check if Koko can finish within h hours at that speed.
  2. Optimized approach: Use binary search to find the minimum valid k instead of testing every speed in order.
  3. Key observation: A slower eating speed takes longer, and a faster speed finishes sooner. Feasibility therefore flips exactly once as k grows, and that single flip is what binary search locates.

The third hint names the pattern. This question belongs to Modified Binary Search, which means you binary search a range of candidate answers rather than a sorted array. The range here is the eating speed, 1 through max(piles), and the test for each candidate is "can Koko finish in h hours at this speed". It is one of the highest-yield entries among the recurring coding interview patterns, because the same move solves shipping capacity, divisor thresholds, and several scheduling questions.

Approach 1: brute force (try all speeds)

Explanation

  • Iterate over possible speeds k from 1 to max(piles) (the size of the largest pile).
  • For each speed k, calculate the total time required by summing up ceil(pile / k) for each pile.
  • If the total hours needed is <= h, then Koko can finish with speed k. Return this k as soon as you find the first that works, which is the minimum possible.
  • If none of the speeds up to max(piles) work, which the constraints rule out, return -1.

Python code

Python3
Python3

. . . .

Complexity analysis

  • Time complexity: O(N * M), where N is the number of piles and M is the size of the largest pile. In the worst case that reaches 10^9 * 10^4 operations, far beyond any time limit. The brute force will time out on large inputs.
  • Space complexity: O(1), since we only use a few extra variables for counting time.

Explanation

  • We can use binary search on the range of possible eating speeds, from 1 to max(piles).
  • Set low = 1 and high = max(piles). While low < high:
    • Choose mid = (low + high) // 2 as a candidate speed.
    • Compute the total hours required at speed mid by summing ceil(pile / mid) for each pile.
    • If the total hours are <= h, then mid is fast enough, possibly faster than needed. Try a smaller speed by setting high = mid.
    • If the total hours are > h, then mid is too slow, so the speed has to go up. Set low = mid + 1.
  • When the loop ends, low equals high, and that value is the smallest speed that finishes within h hours.

Notice what the search never does: it never evaluates most candidate speeds at all. Each test tells you which half of the range still holds the answer, so about log M tests settle it. If that boundary-hunting feels unfamiliar, Find Peak Element drills the same discard-half reasoning on a simpler input, and the mock interview course teaches this question directly in its Koko Eating Bananas lesson.

Python code

Python3
Python3

. . . .

Java code (binary search approach)

Java
Java

. . . .

Note: In the Java code above, (pile + mid - 1) / mid computes the ceiling of pile/mid with integer arithmetic.

Complexity analysis

  • Time complexity: O(N * log M), where N is the number of piles and M is the maximum pile size. The binary search runs in about log M steps, and each step computes the total hours in O(N). That stays fast even at the top of the constraint range.
  • Space complexity: O(1), since the extra space used is minimal.

Edge cases

  1. Single pile: With piles = [10] and h = 5, a speed of 2 is enough, because ceil(10 / 2) is 5 hours. A speed of 1 would need 10 hours, so the answer is 2. Only h = 1 would force a speed of 10.
  2. Plenty of time: If h is very large, say much larger than the total number of bananas, Koko can eat as slowly as 1 banana per hour and still finish. The answer is then 1.
  3. Huge pile sizes: Very large pile values cost the binary search only a few more steps, while a linear scan over speeds becomes hopeless.

Common mistakes

  • Using floor division instead of ceiling when calculating hours, for example sum(pile // k) in Python. That underestimates the hours, because leftover bananas in a pile still occupy a full extra hour.
  • Testing every possible speed on large inputs. The feasible region is monotonic: once a speed works, every faster speed works too. That property is the license to binary search, so use it.
  • Setting high to the sum of all piles rather than max(piles). The search still returns the right answer, but no speed above the largest pile ever helps, since one hour per pile is already the floor on time.

Alternative variations

  • Minimize maximum workload: Instead of time, distribute the piles among several workers and minimize the largest amount any one worker must eat. This is the same load-balancing shape, answered with binary search or a greedy rule.
  • Split Array Largest Sum: Split an array into a given number of subarrays and minimize the largest subarray sum. This also binary searches for an optimal threshold.
  1. Split Array Largest Sum. Partition an array into subarrays so that the largest subarray sum is minimized, with binary search or dynamic programming.
  2. Capacity To Ship Packages Within D Days. Find the minimum ship capacity that clears the packages before a deadline, by binary searching the capacity.
  3. Find Smallest Divisor Given a Threshold. Determine the smallest divisor for which the sum of the quotients stays within a given threshold, by binary searching the divisor.

All three reuse the structure you just applied: define the candidate range, write one feasibility test, then discard half the range per step. Several of them appear on the Blind 75 list, and Grokking the Coding Interview collects them into a single chapter so the pattern, not the individual question, is what you practice.

TAGS
Coding Interview Questions
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which tool is used for Agile methodology?
What is IBM coding assessment?
Pinterest Application Status: How Long Does Pinterest Take to Respond?
Pinterest usually replies to an application within one to two weeks, and gives a decision within one to two weeks of the onsite. Here is how to read your status page.
What does JSX stand for?
What are the tips for coding interviews in Perl?
Who is the CEO of GitLab?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$99

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
About Us
Our Team
Careers
Partners
Contact Us
Become Affiliate
Copyright © 2026 Design Gurus, LLC. All rights reserved.