Two Pointers
Uses two indices that traverse a sorted array (or string) from different positions, often opposite ends, to solve pair or partition problems in O(n) without extra space.
Syntax
twoSum(arr, target) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
arr | number[] | Yes | Sorted array to search within. |
target | number | Yes | The target sum to find a pair for. |
Returns
[number, number] | null — Pair of indices [i, j] such that arr[i] + arr[j] === target, or null.
Examples
// Two-sum on a sorted array
function twoSum(arr, target) {
let lo = 0, hi = arr.length - 1;
while (lo < hi) {
const sum = arr[lo] + arr[hi];
if (sum === target) return [lo, hi];
if (sum < target) lo++;
else hi--;
}
return null;
}
console.log(twoSum([1, 2, 3, 4, 6], 6));
console.log(twoSum([1, 2, 3, 4, 6], 10));
Output
[ 1, 3 ]
null
// Remove duplicates in-place from sorted array (fast/slow pointer variant)
function removeDuplicates(arr) {
if (!arr.length) return 0;
let slow = 0;
for (let fast = 1; fast < arr.length; fast++) {
if (arr[fast] !== arr[slow]) {
slow++;
arr[slow] = arr[fast];
}
}
return slow + 1; // new length
}
const nums = [1, 1, 2, 2, 3, 4, 4];
const newLen = removeDuplicates(nums);
console.log(nums.slice(0, newLen));
Output
[ 1, 2, 3, 4 ]
Notes
| Case | Time | Space |
|---------|------|-------|
| Best | O(n) | O(1) |
| Average | O(n) | O(1) |
| Worst | O(n) | O(n) |
Two pointers is a meta-technique with several variants:
- **Opposite ends** (lo/hi): two-sum, container with most water, trapping rain water.
- **Fast/slow** (tortoise and hare): cycle detection (Floyd's), finding midpoint, removing duplicates.
- **Same direction with condition**: merge of two sorted arrays, partition problems.
The technique requires the array to be sorted for most pair-sum problems.
Without sorting, use a hash map instead (O(n) time, O(n) space). When
combined with sorting, the total complexity is O(n log n).