Find a Target Pair with Two Pointers
Core idea
For an ascending integer list, keep two indices at opposite ends. If their sum is too small, the left value cannot pair with any remaining value to reach the target; move left inward. If too large, discard the right value. Stop when a pair matches or fewer than two candidates remain. Time O(n), auxiliary space O(1) under a bounded-value model.
def has_pair(values, target): left, right = 0, len(values) - 1 while left < right: total = values[left] + values[right] if total == target: return True if total < target: left += 1 else: right -= 1 return Falseprint(has_pair([1, 3, 6, 10], 9))The sum 1+10 is too large; then 1+6 is too small; 3+6 matches.
Respect distinct positions
def has_pair(values, target): left, right = 0, len(values) - 1 while left < right: total = values[left] + values[right] if total == target: return True if total < target: left += 1 else: right -= 1 return Falseprint(has_pair([4], 8))print(has_pair([4, 4], 8))One element cannot be used twice, but two equal values at distinct indices are valid.
Common mistake
The elimination argument depends on sorted input, not on all values being positive. Do not use left <= right, which may reuse one item.
Practice
Check whether two distinct positions sum to a target; test negatives, duplicates, empty and singleton input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Two-pointer elimination
Check your understanding of two pointers.
What is printed?
def has_pair(values, target): left, right = 0, len(values) - 1 while left < right: total = values[left] + values[right] if total == target: return True if total < target: left += 1 else: right -= 1 return Falseprint(has_pair([-3,1,7],4))What is printed?
def has_pair(values, target): left, right = 0, len(values) - 1 while left < right: total = values[left] + values[right] if total == target: return True if total < target: left += 1 else: right -= 1 return Falseprint(has_pair([2],4))If the endpoint sum is too small, which endpoint can be discarded?
What ensures progress?