Scanning & Windows
Binary Search
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
Practice
Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.
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)?
Classic problem
Binary Search (LeetCode 704) — return the index of target in a sorted nums, or
-1. Halve the range each step by comparing against the middle.
Input: nums = [1, 2, 3, 4, 5, 6, 7, 8], target = 8
Output: 7 — nums[7] = 8 equals the target, reached after 4 halvings toward the right edge.
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.