Two pointers use two moving positions to control a search, interval, or pair selection.
The technique often replaces a nested loop with a single pass when movement rules are clear.
Core Idea
The two positions may start at opposite ends and move inward, or both may move from left to right. The key is that each pointer moves in a controlled direction so the total number of moves stays small.
Sorted order often makes the movement rule possible.
Python Example
def has_pair_sum(sorted_values, target):
left = 0
right = len(sorted_values) - 1
while left < right:
total = sorted_values[left] + sorted_values[right]
if total == target:
return True
if total < target:
left += 1
else:
right -= 1
return FalseBecause the list is sorted, each move safely discards some pairs.
Common Confusions
Two pointers is not just “use two variables.” The movement rule must be justified.
If the input is not sorted or does not have a monotonic property, moving one pointer may discard valid answers.
When To Use It
Use two pointers for sorted pair problems, merging, removing duplicates, partitioning, and interval scans where each pointer can move only forward or inward.