Two pointers
Two indexes that move through the data with a rule, never backwards. From opposite ends of a sorted array they find pairs; side by side they rewrite an array in place; one per array they merge.
How to recognise it
- The array is sorted (or you can sort it) and you need a pair or triplet with a target sum or difference.
- You must change the array in place with O(1) extra memory (remove, move, compact values).
- Two sorted arrays must be combined, intersected or walked together.
- Something is compared from both ends inwards (palindromes, water between walls).
The idea in one picture
Two people search a sorted row of numbered cards for a pair that adds up to 50. One starts at the smallest card, one at the largest. If their sum is too small, the person on the small side steps right; too big, the person on the large side steps left. Neither ever steps back, so together they cover the row once. That is the whole trick: a rule tells you which pointer to move, and no pointer moves backwards, so the work is O(n) instead of O(n²).
Three shapes
| Shape | Pointers | Used for |
|---|---|---|
| Opposite ends | left = 0, right = n - 1, move inwards | pair sums on sorted data, palindromes, trapped water |
| Read and write | both start at the front; read scans, write marks the next free slot | removing or moving values in place |
| One per array | i in the first array, j in the second | merging, union, intersection of sorted arrays |
Template: pair with a target sum in a sorted array
left = 0
right = n - 1
while left < right:
sum = nums[left] + nums[right]
if sum == target: found
else if sum < target: left = left + 1 # need bigger
else: right = right - 1 # need smaller
Every pair the loop skips is provably no good: if the sum is too small with the largest remaining partner, nums[left]
cannot be in any pair, so it is safe to drop.
From pairs to triplets and quadruplets
Fix one element with a loop and run the pair template on the rest: 3Sum is O(n²). Fix two and run it on the rest: 4Sum is O(n³). To avoid repeated answers, skip any fixed value equal to the one before it, and skip repeats of the pointer values after recording a match.
A guided example: move the zeros of [0, 1, 0, 3, 12] to the end, keeping order
| read | value | action | array | write |
|---|---|---|---|---|
| 0 | 0 | skip | [0, 1, 0, 3, 12] | 0 |
| 1 | 1 | swap into slot 0 | [1, 0, 0, 3, 12] | 1 |
| 2 | 0 | skip | [1, 0, 0, 3, 12] | 1 |
| 3 | 3 | swap into slot 1 | [1, 3, 0, 0, 12] | 2 |
| 4 | 12 | swap into slot 2 | [1, 3, 12, 0, 0] | 3 |
Common mistakes
- Using opposite-end pointers on an unsorted array. The "move left to grow the sum" rule needs sorted values.
- Forgetting to skip duplicates in 3Sum and 4Sum, which reports the same triplet more than once.
- Overflowing a 32-bit sum in 4Sum, where four values near 10⁹ add up past 2³¹.
- Merging into the front of an array that still holds values you need.
Problems
- Move Zeroeseasyguide ready
- Remove Duplicates from Sorted Arrayeasyguide ready
- Merge Sorted Arrayeasyguide ready
- Union of two sorted arraysmediumguide ready
- Intersection of two sorted arraysmediumguide ready
- 3Summediumguide ready
- 4Summediumguide ready
- Move all the negative elements to one side of the arraymediumguide ready
- find common elements In 3 sorted arraysmediumguide ready
- Find the triplet that sum to a given valuemediumguide ready
- Minimum no. of operations required to make an array palindromemediumguide ready
- find a pair with a given differencemediumguide ready
- Count triplet with sum smaller than a given valuemediumguide ready
- DoubleHelix SPOJmediumguide ready
- Trapping Rain Waterhardguide ready