PPractick

DSA interview question

Koko Eating Bananas

Medium · Algorithms · Topics: binary search on answer, array

The problem

Koko has n piles of bananas and h hours before the guards return. Each hour she picks one pile and eats up to k bananas from it; if the pile has fewer than k, she finishes it and waits for the next hour. She wants to eat slowly, so she needs the minimum speed k that still finishes every pile within h hours. Trying every speed from 1 upwards is far too slow when piles hold 10⁹ bananas. But feasibility is monotonic: any speed faster than a working speed also works. So binary search on k.

Example: piles = [3, 6, 7, 11], h = 8 → 4.

Function signature

int minEatingSpeed(const vector<int>& piles, long long h);  // h >= number of piles

Test cases

Input (piles, h)OutputExplanation
([3, 6, 7, 11], 8)41 + 2 + 2 + 3 = 8 hours
([30, 11, 23, 4, 20], 5)30One hour per pile: the speed must equal the largest pile
([30, 11, 23, 4, 20], 6)23
([1000000000], 2)500000000
([312884470], 312884469)2At speed 1 she'd need one hour too many

(Confirm: h ≥ number of piles, so an answer always exists (speed = max pile); hours per pile = ceil(pile / k).)

How interviewers phrase it

Clarifying questions to ask

  1. Is h at least the number of piles? (Otherwise it's impossible.)
  2. Does leftover time in an hour carry over to another pile? (No.)
  3. How large can the piles and h be? (Sums need 64-bit.)

Follow-ups to expect

  1. "Why is binary search valid here?"
  2. "What's the search range?"
  3. "How do you compute hours for a speed?"
  4. "Complexity?"
  5. "Can you tighten the lower bound?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in