Pattern #04
Binary Search
EssentialHalve a sorted or monotonic search space until you pin the answer.
When to use
The search space is sorted, rotated-sorted, or any monotonic predicate “feasible(mid)”. not only classic “find target in array”.
Recognition cues
- Sorted array (or partially ordered)
- Find first/last/insert position
- Rotated sorted array
- Peak finding with bitonic property
Common pitfalls
- Infinite loop: use lo < hi with exclusive bound, or lo + 1 < hi carefully
- Mid overflow: prefer lo + ((hi - lo) >> 1)
- Confusing lower-bound vs exact match
90-second recognition drill
Which pattern fits best?
- Sorted array (or partially ordered)
- Find first/last/insert position
- Rotated sorted array
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
a[mid] = 5 < 9
How to think about it
Maintain an interval that still contains the answer. The template uses an exclusive upper bound: lo = 0, hi = n, and while lo < hi. The probe is mid = lo + ((hi - lo) >> 1). If nums[mid] < target, the answer is strictly to the right (lo = mid + 1); otherwise it is at mid or to the left (hi = mid). The loop ends at lo == hi, the lower bound. An inclusive loop that sets hi = mid - 1 on a larger midpoint finds the same index when an empty range means absent.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Exact or insert | Lower bound of target. LC 704 returns that index only when the value equals target. LC 35 returns it as the insert position, or n when every value is smaller |
LC 704, LC 35 |
| First and last | Lower bound of target and of target + 1. The last index is one before the second bound. If the first bound is not target, the answer is [-1, -1] |
LC 34 |
| Rotated order | One side of mid is sorted. Compare nums[mid] with an endpoint to see which. Search the sorted side when the target lies inside it. For the minimum, nums[mid] > nums[hi] means the minimum is strictly right of mid |
LC 33, LC 153 |
| Peak | If nums[mid] < nums[mid + 1], the peak is to the right. Neighbors outside the array count as smaller, so an endpoint can be the peak |
LC 162 |
Complexity baseline
O(log n) time, O(1) space for the iterative form.
From template to problem
- Name the predicate before choosing bounds. Exact match, insert position, and a rotated minimum are different tests on the same halving loop.
- Compute
midaslo + ((hi - lo) >> 1)so the probe stays inside the interval. - On a rotated array, decide which side is sorted before testing the target (LC 33). This path’s minimum problem has no duplicates (LC 153).
- A peak search may return an endpoint (LC 162). Do not require both neighbors to exist.
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
/** Binary search template: lower-bound, then exact match. */
export function binarySearch(nums: number[], target: number): number {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < target) lo = mid + 1;
else hi = mid;
}
return lo < nums.length && nums[lo] === target ? lo : -1;
}
/** Binary search template: lower-bound, then exact match. */
export function binarySearch(nums: number[], target: number): number {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < target) lo = mid + 1;
else hi = mid;
}
return lo < nums.length && nums[lo] === target ? lo : -1;
}
- 1#33 Search in Rotated Sorted ArrayGuidemedium
- 2#34 Find First and Last Position of Element in Sorted ArrayGuidemedium
- 3#35 Search Insert PositionGuideeasy
- 4#153 Find Minimum in Rotated Sorted ArrayGuidemedium
- 5#162 Find Peak ElementGuidemedium
- 6#704 Binary SearchGuideeasy