Finding the Left Boundary with Binary Search
Binary search finds the first element that satisfies a monotone predicate by keeping a half-open range and moving the lower bound past every false midpoint. The predicate must be false on a prefix and true on the suffix, and the final lower bound is the answer.
The short answer
Binary search finds the first element that satisfies a monotone predicate by keeping a half-open range [lo, hi) and testing the midpoint. If the predicate is false at the midpoint, the answer lies strictly to the right, so lo moves to mid + 1. If it is true, the midpoint is a candidate, so hi moves to mid. When the range is empty, lo is the first true index, or n if none exists. The predicate must be false for a prefix of the array and true for the remaining suffix; that single precondition is what makes the search correct.
A minimal example
def first_true(lo: int, hi: int, pred) -> int:
"""Smallest i in [lo, hi) where pred(i) is true; hi if none."""
while lo < hi:
mid = lo + (hi - lo) // 2
if pred(mid):
hi = mid
else:
lo = mid + 1
return lo
nums = [1, 3, 3, 5, 8]
i = first_true(0, len(nums), lambda k: nums[k] >= 5)
print(i, nums[i] if i < len(nums) else None) # 3 5
The same shape appears in standard libraries. C++ std::lower_bound returns the first element that is not less than a value; Python's bisect_left returns the leftmost insertion point. Both are this loop with the comparison supplied by the caller.
#include <algorithm>
#include <vector>
std::vector<int> v{1, 3, 3, 5, 8};
auto it = std::lower_bound(v.begin(), v.end(), 5); // first 5
Why this pattern works
The loop maintains an invariant: every index below lo fails the predicate, and every index at or above hi passes it. The boundary is trapped inside [lo, hi), and each iteration removes at least one index from that range, so the loop ends after about log2(n) tests.
Two details prevent common bugs. Compute the midpoint as lo + (hi - lo) // 2 rather than (lo + hi) // 2, because the latter can overflow in fixed-width integer languages. Keep the interval half-open, because an empty range is then a natural way to say "no candidates left"; if the predicate is false everywhere, lo simply reaches hi and the function returns n.
This is not the same as the first binary search most people learn. The "find any match" version returns as soon as it sees a true value. That is wrong for a left boundary when duplicates exist: a true midpoint does not prove there is no true value to its left, so the search must keep narrowing instead of stopping.
What changes the answer
| Input situation | Return value |
|---|---|
| Predicate false at every index | n, one past the end |
| Predicate true at every index | 0 |
| Duplicates satisfying the predicate | Index of the first one |
| Empty array | 0, which equals n |
| Predicate true, then false | No valid answer; precondition broken |
The last row is the failure people miss. "At least x" is monotone on a sorted array; "equal to x" is not, because equal elements form an interior block and both sides fail. For an equality search, run the predicate >= x, then check that the returned index is in range and actually holds x.
Practical checks
Test the three boundary cases explicitly: an empty array, a predicate true only at the final index, and a predicate never true. These catch nearly every off-by-one error. If you need both ends of a run of equal keys, run the routine twice, once with >= x and once with > x; the results form a half-open range and their difference is the count.
When the array holds records sorted by a key, equal keys can make "the first match" ambiguous. The sort that produced the array must then be stable so the first match is also the earliest record in the original order; see stable sorting with equal keys. Boundary tests for this kind of loop are worth writing before the implementation; boundary tests covers the general approach.
Sources
Revision history
- Published
- Updated
- — Initial publication.