DSA · Beginner · Pattern 6 of 11
Binary Search
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
Binary search halves a sorted search space at every step, finding a target or a boundary in O(log n). The most useful form is boundary search: find the first index where a monotone condition becomes true, such as the first element not less than x. Thinking in terms of that predicate avoids most off-by-one errors and also handles rotated arrays, where one half is always sorted.
Signals include a sorted input, queries asking how many elements are at most some value, and constraints such as n up to 10^5 with many queries. In C++, lower_bound and upper_bound perform boundary search directly on sorted ranges.
// First index in [lo, hi) where ok(i) is true; hi if none.
// Requires ok to be monotone: false ... false true ... true.
int firstTrue(int lo, int hi, const function<bool(int)>& ok) {
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (ok(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
// Built-in: int i = lower_bound(a.begin(), a.end(), x) - a.begin();