← All patterns
1 / 32
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

  1. Is the search space sorted, or monotonic in some predicate?
  2. Can you ask a yes/no “is X feasible?” question?
  3. 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: 7nums[7] = 8 equals the target, reached after 4 halvings toward the right edge.

Watch it run

Common pitfalls

Off-by-one in the loop bound (lo < hi vs lo <= hi).

Updating hi = mid - 1 when mid might be the answer.

Overflow on (lo + hi) in languages without big ints.