Binary Search
The Mental Model
Binary search is like playing “guess the number” optimally. Instead of guessing randomly, you always guess the middle. With each guess, you eliminate half the possibilities. This is why binary search is O(log n)—even with a billion elements, you need at most 30 guesses.Pattern Recognition Signals:
- “Minimum/Maximum value that satisfies condition”
- “Find first/last occurrence”
- Sorted array or monotonic property
- Constraints allow O(log n) or O(n log n)
The Two Types of Binary Search
Type 1: Binary Search on Index
Find an element or position in a sorted array.Type 2: Binary Search on Answer
The answer is a number in a range. Check if each candidate answer is valid. The validity forms a monotonic sequence (all NO, then all YES, or vice versa).Template: Binary Search on Index
Finding Exact Element
Finding Lower Bound (First >= Target)
Finding Upper Bound (First > Target)
Template: Binary Search on Answer
This is the game-changer pattern. Many problems that seem impossible become easy with this technique.Classic Pattern: Minimum Maximum
Problem Type: “Minimize the maximum” or “Maximize the minimum” Example: Split array into K subarrays to minimize the maximum subarray sum. Approach: Binary search on the answer (the maximum sum). For each candidate, check if we can split into ≤ K subarrays.Classic Pattern: Kth Element
Problem: Find the Kth smallest element in sorted matrix / merged sorted arrays. Approach: Binary search on the value. Count how many elements are ≤ mid.Common Mistakes
The Binary Search Decision Tree
Advanced: Ternary Search
For unimodal functions (one peak/valley), use ternary search:Practice Problems
Beginner (800-1200)
Intermediate (1200-1500)
Advanced (1500-1800)
Key Takeaways
Monotonic Predicate
Binary search works when canAchieve(x) is monotonic (all false, then all true).
Search on Answer
When asked to minimize/maximize, binary search on the answer is often the key.
Bound Selection
Carefully choose lo and hi. lo = minimum possible, hi = maximum possible.
Off-by-One
Use
lo < hi for bounds, lo <= hi for exact search. Be precise.Next Up
Chapter 7: Sorting & Custom Comparators
Learn strategic sorting techniques and how custom comparators unlock powerful problem-solving approaches.