Move the boundary with a reason.
Use sorted order to eliminate candidate pairs without enumerating them all.
01 Model the idea
Two pointers are useful when moving one boundary can safely rule out a group of candidates. In sorted two-sum, a sum that is too small means the left value is too small even when paired with the largest remaining value. A sum that is too large similarly rules out the right value. That ordering argument makes each boundary movement safe.
No pair excluded by the current boundaries can meet the target.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
COMPARE the boundary sum with the target
MOVE left if too small, right if too large
STOP on a match or crossed boundaries03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def two_sum(values, target):
left, right = 0, len(values) - 1
while left < right:
total = values[left] + values[right]
if total == target: return left, right
if total < target: left += 1
else: right -= 1
return None
print(two_sum([2, 4, 7, 11, 15], 15))(1, 3)
- 1
The returned pair contains distinct indexes. The left<right condition prevents using one position twice.
- 2
Every failed comparison removes at least one boundary, so there are at most linear many pointer moves.
- 3
The input must be sorted. If you sort internally, the total cost and original-index contract change; storing original positions may be necessary.
04 Count the cost
O(n) on already sorted input
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
Test an absent target and a pair formed by equal values at distinct positions.
Reveal one possible solution +
def two_sum(values, target):
left, right = 0, len(values) - 1
while left < right:
total = values[left] + values[right]
if total == target: return left, right
if total < target: left += 1
else: right -= 1
return None
print(two_sum([3, 3], 6))
print(two_sum([1, 2], 9))06 Check your reasoning
What justifies moving a boundary?
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.