Skip to content
ΣDSA Patterns
Menu
Language

Binary Search on Answer

Guide 3 of 6 · Path 3 of 6

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1F
2F
3F
4T
5T
6T
7T
8T

feasible(x) is monotonic

Search the answer domain, not array indices. Example: min feasible speed.

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Koko Eating Bananas

Problem (restated)

Koko has piles of bananas and h hours. She eats at speed k bananas/hour (ceil per pile). Find minimum k so she finishes within h hours.

Intuition

Higher k always finishes no later → monotonic. Binary search k in [1, max(pile)].

Approaches

Binary search on eating speed

Tested only
Time O(n log M)Space O(1)

Idea. lo=1, hi=max(piles). feasible(k)=sum(ceil(pile/k)) ≤ h. Find min k.

Walkthrough. piles=[3,6,7,11], h=8 → k=4.

Trade-offs. Must use integer ceil carefully to avoid floats: (pile + k - 1) / k.

Solution
export function minEatingSpeed(piles: number[], h: number): number {
  let lo = 1, hi = Math.max(...piles);
  const feasible = (k: number) => {
    let hours = 0;
    for (const p of piles) hours += Math.ceil(p / k);
    return hours <= h;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (feasible(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}
export function minEatingSpeed(piles: number[], h: number): number {
  let lo = 1, hi = Math.max(...piles);
  const feasible = (k: number) => {
    let hours = 0;
    for (const p of piles) hours += Math.ceil(p / k);
    return hours <= h;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (feasible(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Template connection

Binary search on answer with a linear feasibility check.

Reflection