The two pointers pattern
Two pointers replaces a nested loop with a single coordinated pass. Two indices move through the data under a rule — converging from both ends, or advancing at different speeds — turning an O(n²) scan into O(n).
The pattern requires structure to exploit, usually sortedness. On a sorted array, comparing the sum at both ends tells you unambiguously which pointer to move, so no candidate is ever missed.
Time and space complexity
| Variant | Time | Space | Typical problem |
|---|---|---|---|
| Converging pointers | O(n) | O(1) | Two Sum II, valid palindrome |
| Fast and slow | O(n) | O(1) | Cycle detection, middle of list |
| Same-direction | O(n) | O(1) | Remove duplicates, move zeroes |
| Two arrays | O(n + m) | O(1) | Merge sorted arrays |
| Three pointers | O(n²) | O(1) | Three Sum after sorting |
How to use this visualizer
Pick a two-pointer problem to load its array and pointers.
Step through and watch which pointer moves after each comparison.
Confirm why moving the other pointer could not produce a better answer.
Track the total number of steps — each pointer crosses the array once.
Frequently asked questions
When the data has structure that tells you unambiguously which pointer to advance — most often a sorted array, a palindrome check from both ends, or a linked list where relative speed matters. If moving a pointer could discard a valid answer, the pattern does not apply and you likely need a hash map or sliding window instead.
Place one pointer at each end and compare their sum to the target. If the sum is too small, advance the left pointer, since only a larger value can help. If it is too large, retreat the right pointer. Each step eliminates one candidate permanently, so the pair is found in O(n) time and O(1) space — no hash map required.
Two pointers advance through the same sequence at different rates, typically one step versus two. If a cycle exists the fast pointer laps the slow one and they meet; if not, fast reaches the end first. The same idea locates the middle of a linked list in one pass, since the slow pointer is halfway when the fast pointer finishes.