patternDSA/Binary Search
Search & Sort → Pattern 03

Binary Search

Eliminate half the search space every single step. The pattern that turns O(n) brute force into O(log n) — and appears in disguise across dozens of problems.

Frequency:★★★★★
·~45 min·Intermediate·10 problems
The Problem With Searching Naively

1,000,000 names — 1,000,000 checks vs 20 checks

Linear Search
1,000,000
worst-case checks
O(n)
Binary Search
20
max checks
O(log n)

A phone book has 1,000,000 sorted names. Linear scan: check every name one by one. Binary search: flip to the middle, throw away half, repeat. Each step eliminates half the remaining candidates.

Real-World Analogies

Real-world intuition before touching code.

Phone Book

Flip to middle. Too early → go right. Too late → go left. You never read every page.

Guessing Game

"1–100. Guess." You say 50. "Higher." You say 75. Found in 7 guesses, not 100.

Dictionary

Looking up 'quarrel'. Open to 'M'. Too early. Each open halves remaining pages.

Core Intuition

The one thing that must be true for binary search to work.

Binary search requires one thing: a monotonic condition. The property you're searching on must change direction exactly once — False to True, or True to False — and never flip back. When that holds, you can look at the midpoint and say: "the answer is definitely not in that half." You throw it away forever.

Works when
Search space is sorted (or monotonic)
Midpoint can be tested in O(1) or O(n)
Discarding half doesn't lose the answer
Fails when
Data is unsorted with no monotonic model
Property tested has no clear boundary
Need to check all candidates (no elimination)

Pattern Recognition

See these → reach for Binary Search immediately.

These keywords = Binary Search
"sorted array" or "sorted matrix"
"find minimum / maximum" + condition
"search in O(log n)"
"rotated sorted array"
"first position" or "last position"
"minimum speed / capacity to achieve X"
"kth smallest in sorted structure"
Probably NOT Binary Search
Unsorted array with no ordering
Need to find all occurrences
Graph / tree traversal required
Multiple conditions that can't collapse
Need the actual path, not just the value