Two Pointers
Two pointers is a technique that walks a sequence with two indexes that move toward a goal, often turning an O(n^2) pair scan into O(n) after a sort.
Detailed Explanation
A nested loop that asks something about arr[i] and arr[j] is O(n^2). If the array is sorted, the pair you want often moves the indexes in only one direction. That is two pointers.
The opposite-ends pattern starts lo at 0 and hi at length - 1. You look at arr[lo] + arr[hi]. Too small, increment lo. Too large, decrement hi. Each step discards an index, so you get O(n) after an O(n log n) sort. Two-sum on a sorted array, container-with-most-water, and palindrome checks on a string are this shape.
The same-direction pattern (also a sliding window's skeleton) advances right every step and pulls left forward when a constraint breaks. Removing duplicates in place, partitioning, and merging two sorted arrays (i on A, j on B) are this shape.
The fast and slow pattern is two pointers on a list: slow moves one node, fast moves two. They meet if there is a cycle. Slow at the start and fast at n, then walk together, finds the nth-from-end.
Invariants matter more than the code. Write down what lo and hi mean after each update. If both can move on the same iteration without a clear reason, you probably dropped a case.
Strings and arrays of UTF-16 code units: a pointer is an index, not a "character". Surrogate pairs make s[i] a half-character. For user-facing text, iterate by code points ([...s] or for (const ch of s)) first.
What it costs you: a sort that you forgot to budget, and a wrong move on duplicates (lo++ once when you needed to skip a run). Two pointers do not help when the predicate is not monotonic in the indexes.
Reach for two pointers when a sorted pair, a window, or a linked-list race is the problem. Reach for a Map when the pair is "seen before" rather than "ends of a sorted range" (unsorted two-sum). Reach for nested loops when n is tiny and the logic is clearer.
Code Examples
function twoSumSorted(arr, target) {
let lo = 0;
let hi = arr.length - 1;
while (lo < hi) {
const sum = arr[lo] + arr[hi];
if (sum === target) return [lo, hi];
if (sum < target) lo += 1;
else hi -= 1;
}
return null;
}
console.log(twoSumSorted([1, 2, 4, 7, 11], 11)); // => [ 1, 3 ]function isPalindrome(s) {
let lo = 0;
let hi = s.length - 1;
while (lo < hi) {
if (s[lo] !== s[hi]) return false;
lo += 1;
hi -= 1;
}
return true;
}
console.log(isPalindrome("level")); // => true
console.log(isPalindrome("loop")); // => falsefunction mergeSorted(a, b) {
const out = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
out.push(a[i]);
i += 1;
} else {
out.push(b[j]);
j += 1;
}
}
return out.concat(a.slice(i), b.slice(j));
}
console.log(mergeSorted([1, 4], [2, 3, 5])); // => [ 1, 2, 3, 4, 5 ]Common Gotchas
Unsorted two-sum is a `Map`, not two pointers
sort first only if you do not need original indexes, or keep index pairs while sorting.
Duplicate values need an extra skip
after a match, move past the run of equals if the problem wants unique pairs.
Fast/slow on a list needs `fast && fast.next`
otherwise `.next.next` throws at the end.
Indexes are code units in a JS string
emoji can occupy two indexes.