Modified Binary Search
Find the first matching position using a shrinking boundary.
python, binary search, boundary, sortedSearch for a boundary
Ordinary binary search can stop at any match. To find the first match, keep searching left when a middle value equals the target. This works because the values are sorted in nondecreasing order.
Python illustration
def first_position(values, target):
left, right = 0, len(values)
while left < right:
middle = (left + right) // 2
if values[middle] < target:
left = middle + 1
else:
right = middle
if left < len(values) and values[left] == target:
return left
return None
print(first_position([1, 2, 2, 2, 5], 2))
Prepared output: 1.
See the reasoning
Follow the example one step at a time
Shrink a half-open range toward the first 2. This is a prepared teaching demonstration, not live code execution.
Inspect middle
[1, 2, 2, 2, 5] left=0 right=5 middle=2
Value 2 could be the first match, so retain it and search left.
Why the boundary survives
Indices below left hold values smaller than the target. Indices at or
beyond right are not needed to find the first position whose value is at
least the target. The half-open candidate range shrinks until the insertion
boundary is found; the final equality check distinguishes absence. Time is
O(log n) and extra space O(1), assuming constant-time indexing and comparable
values. An arbitrary unsorted list has no such monotone boundary. Python's
bisect_left provides a related insertion point.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
