Overview
The Two Pointers technique is a staple array pattern for problems on a sorted array. Instead of checking every pair with nested loops, it places one pointer at the start and another at the end, then moves them toward each other based on how their combined value compares to a target.
For the classic pair-sum problem — find two numbers that add up to a target — this turns an O(n²) brute-force scan into a single O(n) pass with O(1) extra space. The sorted order is what makes the decision to move a pointer safe and unambiguous.
How Two Pointers works
- Start with the array sorted in ascending order — this precondition is what the technique relies on.
- Place a left pointer on the first element and a right pointer on the last element.
- Compute the sum of the two pointed-to values and compare it with the target.
- If the sum is too small, move the left pointer right to increase it; if it is too large, move the right pointer left to decrease it.
- Stop when the sum equals the target (a pair is found) or the pointers cross (no such pair exists).
When to use it
- The Two Sum on a sorted array and 3Sum problems — cornerstone coding-interview questions.
- Detecting a palindrome or reversing an array in place by walking pointers inward from both ends.
- Merging two sorted arrays and the container-with-most-water problem, where each step advances the more limiting pointer.
- Any problem where a sorted array lets you prune half the search space with a single comparison.
Complexity analysis
Each pointer only ever moves inward, so together they traverse the array at most once, giving O(n) time. Only two indices are stored, so extra space is O(1). Note the O(n) figure assumes the array is already sorted; if you must sort first, that step dominates at O(n log n).
Frequently asked questions
Why does the array have to be sorted?
Sorting is what makes each move unambiguous: when the sum is too small the answer can only lie to the right, and when it is too large only to the left. On an unsorted array that guarantee disappears, so you would need a hash set instead.
How is Two Pointers better than a nested-loop brute force?
A brute-force pair search checks every combination in O(n²). Two Pointers examines each element at most once, reducing the pair-sum search to O(n) time and O(1) space on a sorted array.
Can Two Pointers find all pairs, not just one?
Yes. After finding a valid pair, move both pointers inward (skipping duplicates) and keep scanning until they cross. This is exactly how 3Sum uses an inner two-pointer sweep to collect every unique triplet.