Overview
Binary search is a fundamental algorithm that finds a target in a sorted array in O(log n) time. Beyond simple searches, it’s used for finding boundaries, optimizing functions, and solving a wide range of problems.Core Concept
Binary search works on monotonic functions - functions that are either non-decreasing or non-increasing. The key insight:- If a property holds at position
mid, it holds for all positions on one side - This allows eliminating half the search space each iteration
Template I: Finding First Valid Position
Finds the smallest index whereworks(index) returns true.
Template II: Finding Last Invalid Position
Finds boundary whenhigh - low > 1 termination is needed.
Template III: Jump Search Style
Uses exponential/binary jumping for unbounded search.Binary Search on Real Values
Template I: Real Values (Relative Error)
Template II: Real Values (Fixed Iterations)
Template III: Real Values (Absolute Check)
STL Binary Search Functions
lower_bound
Finds first element ≥ valueupper_bound
Finds first element > valuebinary_search
Checks if element existsCount occurrences
Common Applications
1. Binary Search the Answer
When answer has monotonic property but direct computation is hard.2. Finding Peak Element
3. Rotated Sorted Array
4. Square Root
5. Kth Smallest Element in Sorted Matrix
Common Patterns
Pattern 1: Minimize Maximum
Pattern 2: Maximize Minimum
Tips and Tricks
1. Avoiding Integer Overflow
2. Inclusive vs Exclusive Bounds
3. Finding Exact vs Closest
4. Rounding in Real-Valued Search
Complexity Analysis
| Scenario | Time | Space |
|---|---|---|
| Binary search in array | O(log n) | O(1) |
| Binary search the answer | O(log(range) × check) | O(1) |
| Real-valued search | O(iterations × check) | O(1) |
Common Mistakes
- Off-by-one errors: Carefully choose inclusive/exclusive bounds
- Infinite loops: Ensure search space shrinks each iteration
- Wrong mid calculation: Use
low + (high - low) / 2 - Forgetting to sort: Binary search requires sorted input
- Wrong comparison: Ensure monotonic property holds
Why Binary Search Works
Why Binary Search Works
Binary search exploits the monotonic property: if a predicate is false at position i, it’s false for all positions before i (or after i, depending on direction).Invariant maintained:
- All positions < low: predicate is false
- All positions ≥ high: predicate is true
- Answer is in range [low, high)
- Check middle position
- Update low or high based on result
- Search space reduces by half