Scanning & Windows
Binary Search
🪓
Picture this
A hooded executioner cleaves every problem clean in half — again, and again, and again.
When you see it
Signal words
If the prompt uses any of these, this pattern should come to mind first.
sortedminimum possiblemaximum possiblefeasible?monotonicfind the boundary
Ask yourself
- Is the search space sorted, or monotonic in some predicate?
- Can you ask a yes/no “is X feasible?” question?
- Are you minimizing a maximum (or vice-versa)?
Canonical template
let lo = 0, hi = a.length - 1;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (feasible(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
Common pitfalls
Off-by-one in the loop bound (
lo < hivslo <= hi).
Updating
hi = mid - 1whenmidmight be the answer.
Overflow on
(lo + hi)in languages without big ints.