MohitDecodes
Back to blogsDSA

Binary Search on Answer: The Pattern Behind Medium-Hard Problems

October 18, 2026 · 7 min read

Problems like Koko Eating Bananas, Allocate Minimum Pages, and Aggressive Cows confuse candidates because the input array isn't what you binary search — the **answer range** itself is monotonic.

How to spot Binary Search on Answer

Ask: if speed `k` works, will every speed `> k` also work (or vice versa)? Whenever feasibility switches cleanly from `false, false, false` to `true, true, true` across a numeric range `[low, high]`, you can binary search for the boundary in `O(log(range) * checkCost)`.

let low = minPossible, high = maxPossible, ans = high;
while (low <= high) {
  const mid = low + Math.floor((high - low) / 2);
  if (canFinish(mid)) {
    ans = mid;
    high = mid - 1; // try smaller valid answer
  } else {
    low = mid + 1;
  }
}

Writing a separate boolean `canFinish(mid)` helper keeps the binary search loop clean and turns tricky optimization problems into simple simulation checks.