Binary Search
Binary Search finds a target in a sorted search space by repeatedly halving the interval.
KEY TAKEAWAYS
- Sorted Input: The input must be sorted or monotonic. This is the primary trigger for Binary Search.
- Logarithmic Time: Reduces linear scan to .
- Transition Point: Many binary search problems can be reframed as finding a boundary between two properties (e.g.,
truevsfalse,smallvsbig).
1. TRANSITION-POINT RECIPE
To avoid off-by-one errors and infinite loops, use this robust recipe:
- Define
is_before(val): A helper function that returnstruefor elements in the first half (the "before" region) andfalsefor the second half (the "after" region). The range must be monotonic: alltrues must come before allfalses. - Initialize Boundaries: Set
landrto cover the entire possible range.- Invariant:
lis always in the "before" region, andris always in the "after" region.
- Invariant:
- Loop Condition:
while r - 1 > l. This ensures we stop whenlandrare adjacent (the transition point). - Update Logic:
- Calculate
mid = (l + r) // 2. - If
is_before(mid), movel = mid(keeplin "before"). - Else, move
r = mid(keeprin "after").
- Calculate
- Return: Return
lorrdepending on whether you need the last element of the "before" region or the first element of the "after" region.
2. GRID FLATTENING
For 2D grid problems that require binary search or iteration as if it were a 1D array, map coordinates [r, c] to a flat index i:
- 2D to 1D:
i = r * Cols + c - 1D to 2D:
r = i // Cols,c = i % Cols
3. GUESS-AND-CHECK (BINARY SEARCH ON ANSWER)
If an optimization problem asks for a minimum or maximum value satisfying a condition, and the condition is monotonic (if works, then all work, or vice versa), you can binary search on the answer space.
- Range: Define the minimum and maximum possible values for the answer.
- Check Function: Write a
check(value)function that returnstrueif the value is valid. - Search: Use binary search to find the boundary where
check(value)flips fromtruetofalse.
Practice Problems
Binary Search
Practice this problem with interactive visualization.
Search Insert Position
Practice this problem with interactive visualization.
Find Minimum in Rotated Sorted Array
Practice this problem with interactive visualization.
Search in Rotated Sorted Array
Practice this problem with interactive visualization.
Beyond Cracking the Coding Interview
Valley Bottom
* it can be split into a non-empty prefix and a non-empty suffix,
2-Array 2-Sum
Practice this problem with interactive visualization.
Target Count Divisible By K
Practice this problem with interactive visualization.
Race Overtaking
Practice this problem with interactive visualization.
Search in Sorted Grid
Practice this problem with interactive visualization.
Search in Huge Array
Practice this problem with interactive visualization.
Min-Subarray-Sum Split
Practice this problem with interactive visualization.
Water Refilling
Practice this problem with interactive visualization.
Min Pages Per Day
Practice this problem with interactive visualization.
Tide Aerial View
Practice this problem with interactive visualization.