Binary Search

Binary Search

Signal

Sorted array, find a boundary, or O(log n) required

Template

Find the monotonic yes/no predicate; while lo <= hi.

Worked example (1)

#7

Binary Search on the Answer

Binary Search on Answer

Piles of bananas and h hours are given. Choose the smallest integer eating-speed such that all piles can be finished within h hours.

function minEatingSpeed(piles: number[], h: number): number {
  const hoursNeeded = (speed: number): number =>
    piles.reduce((sum, p) => sum + Math.ceil(p / speed), 0);
  let lo = 1, hi = Math.max(...piles);
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (hoursNeeded(mid) <= h) hi = mid;  // fast enough → try slower
    else lo = mid + 1;                    // too slow → speed up
  }
  return lo;
}
Insight

You binary-search a value range, not an array — the giveaway is "minimize x subject to a feasibility check."