How the two-pointer technique works
The two-pointer technique tracks two positions in the same collection. Each pointer moves according to the result of the current comparison.
This technique often replaces a nested search with one pass. It works well with sorted arrays, linked lists, pairs, triplets, and subarrays.
When to consider two pointers#
Look for two pointers when the input is already sorted. You can also use them when sorting does not remove information that you need.
For example, suppose you need to find two values in a sorted array whose sum matches a target. Start one pointer at each end:
function hasPairWithSum(values: readonly number[], target: number): boolean { let left = 0; let right = values.length - 1;
while (left < right) { const sum = values[left] + values[right];
if (sum === target) { return true; }
if (sum < target) { left += 1; } else { right -= 1; } }
return false;}Move the left pointer when the sum is too small. Move the right pointer when the sum is too large.
Each pointer visits the array at most once. The algorithm uses O(n) time and O(1) extra space.
If you must return original indexes, keep them before sorting. Sorting an unsorted array changes those indexes.
Problems to practice#
These problems use different forms of the same technique:
You can find more examples in the two-pointer problem list on LeetCode.