Shrink a Sorted Interval with Binary Search
Core idea
Binary search requires ascending sorted input. Lower bound is the first index where the value is at least the target, or len(values) if none. Maintain a half-open interval [lo, hi): values before lo are smaller; values at or after hi are at least the target. Each step shrinks the uncertain interval. With constant-time indexing and comparisons, search uses O(log n) time and O(1) auxiliary space.
def lower_bound(values, target): lo, hi = 0, len(values) while lo < hi: mid = (lo + hi) // 2 if values[mid] < target: lo = mid + 1 else: hi = mid return loprint(lower_bound([2, 4, 4, 9], 4))print(lower_bound([2, 4, 4, 9], 8))The result is the leftmost insertion position, not necessarily an exact match.
Verify a candidate using bisect
from bisect import bisect_leftvalues = [3, 7, 11]for target in (7, 8, 12): i = bisect_left(values, target) print(i if i < len(values) and values[i] == target else -1)bisect_left returns the insertion position; verify bounds and equality to find an exact match.
Common mistake
Never apply binary search to unsorted values. Sorting first costs work and can change original indices. Updating lo to mid instead of mid+1 in the smaller branch may prevent progress.
Practice
Implement lower_bound for an ascending list; test duplicates, a gap, an empty list and a target beyond the end.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Binary search bounds
Check your understanding of binary search.
What is printed?
def lower_bound(values, target): lo, hi = 0, len(values) while lo < hi: mid = (lo + hi) // 2 if values[mid] < target: lo = mid + 1 else: hi = mid return loprint(lower_bound([1,3,3,5],3))What is printed?
from bisect import bisect_leftprint(bisect_left([],6))What precondition is essential?
Does a lower bound always identify an equal value?