patternjavascriptTip
Two-pointer technique eliminates the inner loop in sorted array problems
Viewed 0 times
two pointerpair sumsorted arrayin-placeleft right pointer
Problem
Problems like 'find pair summing to target' or 'remove duplicates in-place' look like they need O(n^2) nested loops. Writing nested loops is the default instinct but it's often unnecessary for sorted or processable-in-order data.
Solution
Use two pointers starting at opposite ends (or both at the start for slow/fast pattern). Move them toward each other based on a comparison condition. This collapses the nested loop into a single O(n) pass.
Why
The key insight is that sorted order gives you information: if sum is too large, move the right pointer left; if too small, move left pointer right. Each pointer moves at most n times, giving O(n) total.
Gotchas
- Two-pointer only works reliably on sorted arrays for sum problems — sort first if needed (adds O(n log n))
- Fast/slow pointer variant detects cycles in linked lists (Floyd's algorithm)
- For finding triplets (3Sum), fix one element and apply two-pointer to the rest — O(n^2) not O(n^3)
Code Snippets
Two-pointer pair sum and remove duplicates
// Find pair summing to target in sorted array — O(n)
function twoSum(sorted, target) {
let lo = 0, hi = sorted.length - 1;
while (lo < hi) {
const sum = sorted[lo] + sorted[hi];
if (sum === target) return [lo, hi];
else if (sum < target) lo++;
else hi--;
}
return null;
}
// Remove duplicates in-place from sorted array — O(n)
function removeDups(arr) {
let write = 1;
for (let read = 1; read < arr.length; read++)
if (arr[read] !== arr[read - 1]) arr[write++] = arr[read];
return write; // new length
}Context
Problems on sorted arrays involving pairs, removing elements in-place, or merging
Revisions (0)
No revisions yet.