Binary Search — The Complete Guide
Master Binary Search from first principles. Learn to recognize it instantly, handle tricky boundary conditions, and confidently solve interview questions.
Intuition from Scratch
Why does this pattern exist?
Imagine you're looking for a word in a physical dictionary. You don't start at page 1 and read every page — you open to the middle. If your word comes after the middle page, you ignore the entire first half. If it comes before, you ignore the second half. Each step cuts the remaining pages in half. A 1,000-page dictionary takes at most ~10 steps instead of 1,000.
That's Binary Search. It works whenever the data has a monotonic property — something that's consistently true on one side and false on the other. In a sorted array, everything to the left of the target is smaller and everything to the right is larger. This lets you eliminate half the candidates with each comparison, giving O(log n) instead of O(n).
But Binary Search goes far beyond "find a value in a sorted array." Any time you can define a condition that partitions a search space into two halves — one where the answer can't be and one where it might be — you can binary search. This includes searching on the answer itself ("what is the minimum speed such that...").
Analogies to Build Intuition
The Dictionary Lookup
Open to the middle. Is your word before or after? Ignore the wrong half. Repeat. Each step halves the remaining pages. 1,000 pages → 10 steps. That's O(log n).
The Number Guessing Game
'I'm thinking of a number between 1 and 100. I'll tell you higher or lower.' The optimal strategy? Always guess the middle. You'll find any number in at most 7 guesses (log₂ 100 ≈ 7).
The Balance Scale
You have 8 coins, one is heavier. Put 4 on each side of a scale. The heavier side has the fake coin. Split that group of 4 in half. Three weighings find the coin among 8. That's binary search on physical objects.
What kind of problems does it solve?
Binary Search is your go-to when:
- You need to find a target in a sorted array
- You need to find the first/last position of a value
- You need to find the insertion point for a value
- You need to search on the answer (minimize/maximize a value that satisfies a condition)
- The problem has a monotonic predicate: false...false, true...true
- You see an O(log n) time requirement
The core insight
Binary Search works whenever you can define a boolean condition that is false for all values below some threshold and true for all values above it (or vice versa). You're searching for the boundary where the condition flips. The sorted array case is just one instance of this — the condition is "is arr[mid] ≥ target?"