The two pointers pattern: how to spot it
Updated
Two pointers walk the input from two places at once, usually the two ends of a sorted array or string, and each step rules out a whole set of answers. That is how an O(n²) pair search becomes O(n).
When to reach for it
- The input is sorted, or sorting it does not lose anything you need to return.
- You are looking for a pair (or a triple, by fixing one value) that meets a target.
- The question compares the two ends of something, like a palindrome or a container.
- Moving one end can only make the answer better or worse in a predictable direction.
The usual shape
left, right = 0, len(items) - 1
while left < right:
total = items[left] + items[right]
if total == target:
return left, right
if total < target:
left += 1 # need bigger: drop the smallest
else:
right -= 1 # need smaller: drop the largest4 LeetCode two pointers problems, easiest first
- Valid Palindrome easy
Skip junk, lowercase, then close the gap. Mismatch is the answer.
- Two Sum II medium
Sorted input: too small, advance left; too large, retreat right.
- 3Sum medium
Sort, fix i, then two-sum the suffix. Skip duplicates at every pointer.
- Container With Most Water medium
Area is limited by the shorter wall. Move that end; the other cannot help yet.
Skills these problems use
Each one has a free lesson with worked examples and a drill.
- Place opposite-end pointers
- Target-sum with opposite pointers
- Require sorted order before facing pointers
- Move left when the pair sum is too small
- Fix one index then face the rest
- Skip equal neighbors after a hit
- Close the gap from both ends
- Decide which end to advance
check which skills you have 10 minutes, free, no account.