Find where a value belongs.
Search for insertion boundaries instead of an arbitrary duplicate match.
01 Model the idea
Lower bound finds the first position whose value is not less than a target. Upper bound finds the first position whose value is greater. Their difference counts occurrences in sorted data. Using a half-open interval [low, high) gives a useful boundary-search pattern: every answer lies between zero and len(values), including an insertion position after the last element.
Everything before low fails the boundary condition; everything at or after high satisfies it.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
KEEP a half-open candidate interval
DISCARD the half known to lie below the boundary
RETURN the meeting position03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
from bisect import bisect_left, bisect_right
values = [2, 4, 4, 4, 9]
left, right = bisect_left(values, 4), bisect_right(values, 4)
print(left, right)
print("occurrences:", right - left)
print("insert 12 at:", bisect_left(values, 12))1 4 occurrences: 3 insert 12 at: 5
- 1
The lower position points to the first 4; the upper position lies after the last 4. These are boundaries, not always valid element indexes.
- 2
For an absent target both boundaries can be the same. Test index < len(values) before reading values[index].
- 3
bisect finds a boundary in logarithmic comparisons. Inserting into a Python list at that position still shifts elements and can take linear time.
04 Count the cost
O(log n) boundary search; O(n) list insertion
O(1) auxiliary
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Implement lower bound using a half-open interval and test duplicates and an absent large target.
Reveal one possible solution +
def lower_bound(values, target):
low, high = 0, len(values)
while low < high:
middle = (low + high) // 2
if values[middle] < target: low = middle + 1
else: high = middle
return low
print(lower_bound([2, 4, 4, 9], 4))
print(lower_bound([2, 4, 4, 9], 12))06 Check your reasoning
What is the difference between upper and lower bound for a target?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.