Finding a Lower Bound Among Duplicate Values
The lower bound of a target in a sorted sequence is the earliest position whose value is at least the target, or the end if no such position exists.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace the boundary
For 2, 4, 4, 7 and target four, the lower bound is one though position two holds an equal value. A first true predicate using “value at least four” captures that distinction.
Use a second comparison when needed
The first value greater than four lies at three. The difference of these two indices is two, the count of fours. Sorted range queries use the same pair of boundaries.[1]
Keep a matching midpoint eligible as a boundary
For sorted keys [3, 8, 8, 8, 11, 15], lower bound of eight returns one. Finding eight at midpoint three proves that index three is late enough, so the search tightens its upper bound instead of returning it. See binary search by hand.
[0,6) → middle 3 has 8 → high 3
[0,3) → middle 1 has 8 → high 1
[0,1) → middle 0 has 3 → low 1
Answer 1
Check the neighbors around the returned cut
Every element before lower bound is strictly smaller than the target. Every element after the cut is at least the target. At the outer boundaries one of these ranges is empty. Test an all-equal array and a target above that common value.