Two indices instead of two loops
When data is sorted, you often do not need a nested loop to find a pair that meets some condition. The two pointers pattern places one index at the start and another at the end, then moves them toward each other based on what the current pair tells you.
The convergent walk
For a classic pair sum problem you compare the sum of the values at both pointers against a target.
- If the sum is too small, move the left pointer right to pick a larger value.
- If the sum is too large, move the right pointer left to pick a smaller value.
- If the sum matches, you have found the pair.
Because each step discards one end of the search space, the pointers meet after one linear pass instead of checking every pair.
Beyond pair sums
The same idea drives many tasks: removing duplicates in place, reversing an array, partitioning around a pivot, and merging two sorted lists. A same direction variant uses a slow and a fast pointer over one array to compact or filter elements.
Key idea
On sorted data, two converging pointers replace a nested loop because each comparison lets you discard one whole end of the remaining search range.