Binary Search · Pattern 1 of 8
Exact search and binary search inside a design
Find an exact value in a sorted array, then use the same loop inside data structures that are sorted by time or by running sum.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- A sorted array and one exact value to find
- Events stored in time order, queried as "the latest value at or before time t"
- Picking an index by weight, using a running (prefix) sum
The template
int search(int[] a, int target) {
int lo = 0, hi = a.length - 1; // the answer is in [lo, hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) lo = mid + 1; // target is right of mid
else hi = mid - 1; // target is left of mid
}
return -1; // not found
} def search(a, target):
lo, hi = 0, len(a) - 1 # the answer is in [lo, hi]
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1 # target is right of mid
else:
hi = mid - 1 # target is left of mid
return -1 # not found int search(const vector<int>& a, int target) {
int lo = 0, hi = (int)a.size() - 1; // the answer is in [lo, hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) return mid;
if (a[mid] < target) lo = mid + 1; // target is right of mid
else hi = mid - 1; // target is left of mid
}
return -1; // not found
} function search(a, target) {
let lo = 0, hi = a.length - 1; // the answer is in [lo, hi]
while (lo <= hi) {
const mid = (lo + hi) >>> 1;
if (a[mid] === target) return mid;
if (a[mid] < target) lo = mid + 1; // target is right of mid
else hi = mid - 1; // target is left of mid
}
return -1; // not found
} The variations
-
1Exact match
Closed range
[lo, hi], loop whilelo <= hi, return on a hit and step pastmidotherwise. This is the classic version every other pattern builds on. -
2Binary search inside a design
Data that only ever grows in time order is already sorted. Store it in a list per key, then binary search the query: the last entry with time ≤ t, or the first running sum ≥ a random number.
Now you solve- Snapshot Array Medium Stuck? solution
- Random Pick with Weight Medium Stuck? solution
Mistakes to avoid
- Using
lo < hiwith this template and never checking the last element. - Forgetting that a design problem often wants "at or before t", which is an upper bound minus one, not an exact match.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.