DSA · Intermediate · Pattern 2 of 10
Binary Search on Answer
13 problems.
Your progress0%
- 1st Visit
- 0/13
- 2nd Visit
- 0/13
- Revise
- 0/13
About this pattern
When the answer is a number and you can cheaply check whether a candidate value is feasible, binary search over the answer instead of over an array. The key is monotonicity: if a speed, capacity or height x works, then every larger (or every smaller) value works too. Write a feasible(x) check, usually a greedy O(n) pass, and search for the boundary between infeasible and feasible values.
Signals include phrases such as minimise the maximum, maximise the minimum, or the smallest value such that, together with answers far too large to enumerate. Total cost is O(n log R), where R is the range of possible answers.
// Smallest x in [lo, hi] with feasible(x) true (feasible is monotone).
long long lo = minPossible, hi = maxPossible;
while (lo < hi) {
long long mid = lo + (hi - lo) / 2;
if (feasible(mid)) hi = mid; // mid works; try smaller
else lo = mid + 1; // mid fails; go larger
}
// Largest x that works: mid = lo + (hi - lo + 1) / 2;
// if (feasible(mid)) lo = mid; else hi = mid - 1;