Two Pointers
Two indices moving through a sequence — from both ends or in the same direction — to replace O(n²) pair searches with O(n).
The two pointers pattern uses two indices that move through the data according to a rule. It turns many O(n²) "check every pair" problems into a single O(n) pass.
- The input is sorted (or can be sorted) and you need a pair / triplet meeting a condition.
- You must modify an array in place (remove duplicates, move zeros, partition).
- You compare elements from both ends (palindromes, container with most water).
- You merge or compare two sorted sequences.
Variant 1: opposite ends
Start L at the beginning and R at the end. Each step, look at the pair and move whichever pointer can only improve things. Every move discards possibilities that provably can't be the answer.
int[] twoSumSorted(int[] a, int target) {
int l = 0, r = a.length - 1;
while (l < r) {
int sum = a[l] + a[r];
if (sum == target) return new int[]{l, r};
if (sum < target) l++; // need a bigger sum
else r--; // need a smaller sum
}
return new int[]{-1, -1};
}def two_sum_sorted(a, target):
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == target:
return [l, r]
if s < target:
l += 1 # need a bigger sum
else:
r -= 1 # need a smaller sum
return [-1, -1]function twoSumSorted(a: number[], target: number): [number, number] {
let l = 0, r = a.length - 1;
while (l < r) {
const sum = a[l] + a[r];
if (sum === target) return [l, r];
if (sum < target) l++;
else r--;
}
return [-1, -1];
}Why it's correct: if a[l] + a[r] < target, then a[l] paired with anything left of r is even smaller — so a[l] can never be part of the answer and is safely discarded.
3Sum: fix one, two-pointer the rest
Sort, then for each i run two pointers on the suffix for target −a[i]. Skip equal neighbours to avoid duplicate triplets. O(n²).
List<List<Integer>> threeSum(int[] a) {
Arrays.sort(a);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < a.length - 2; i++) {
if (i > 0 && a[i] == a[i - 1]) continue; // skip duplicate anchors
int l = i + 1, r = a.length - 1;
while (l < r) {
int s = a[i] + a[l] + a[r];
if (s < 0) l++;
else if (s > 0) r--;
else {
res.add(List.of(a[i], a[l], a[r]));
while (l < r && a[l] == a[l + 1]) l++; // skip duplicates
while (l < r && a[r] == a[r - 1]) r--;
l++; r--;
}
}
}
return res;
}def three_sum(a):
a.sort()
res = []
for i in range(len(a) - 2):
if i and a[i] == a[i - 1]:
continue
l, r = i + 1, len(a) - 1
while l < r:
s = a[i] + a[l] + a[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
res.append([a[i], a[l], a[r]])
while l < r and a[l] == a[l + 1]: l += 1
while l < r and a[r] == a[r - 1]: r -= 1
l += 1; r -= 1
return resfunction threeSum(a: number[]): number[][] {
a.sort((x, y) => x - y);
const res: number[][] = [];
for (let i = 0; i < a.length - 2; i++) {
if (i > 0 && a[i] === a[i - 1]) continue;
let l = i + 1, r = a.length - 1;
while (l < r) {
const s = a[i] + a[l] + a[r];
if (s < 0) l++;
else if (s > 0) r--;
else {
res.push([a[i], a[l], a[r]]);
while (l < r && a[l] === a[l + 1]) l++;
while (l < r && a[r] === a[r - 1]) r--;
l++; r--;
}
}
}
return res;
}Variant 2: same direction (read / write pointers)
A fast pointer scans every element; a slow pointer marks where the next kept element should be written. Used for in-place filtering.
int removeDuplicates(int[] a) {
if (a.length == 0) return 0;
int w = 1; // next write position
for (int r = 1; r < a.length; r++)
if (a[r] != a[w - 1]) a[w++] = a[r];
return w; // new length
}
void moveZeroes(int[] a) {
int w = 0;
for (int r = 0; r < a.length; r++)
if (a[r] != 0) { int t = a[w]; a[w++] = a[r]; a[r] = t; }
}def remove_duplicates(a):
if not a:
return 0
w = 1
for r in range(1, len(a)):
if a[r] != a[w - 1]:
a[w] = a[r]
w += 1
return w
def move_zeroes(a):
w = 0
for r in range(len(a)):
if a[r] != 0:
a[w], a[r] = a[r], a[w]
w += 1function removeDuplicates(a: number[]): number {
if (!a.length) return 0;
let w = 1;
for (let r = 1; r < a.length; r++) if (a[r] !== a[w - 1]) a[w++] = a[r];
return w;
}
function moveZeroes(a: number[]) {
let w = 0;
for (let r = 0; r < a.length; r++)
if (a[r] !== 0) { [a[w], a[r]] = [a[r], a[w]]; w++; }
}Variant 3: two sequences
One pointer per input: merging two sorted arrays, checking whether one string is a subsequence of another, intersecting sorted lists.
int maxArea(int[] h) {
int l = 0, r = h.length - 1, best = 0;
while (l < r) {
best = Math.max(best, Math.min(h[l], h[r]) * (r - l));
if (h[l] < h[r]) l++; else r--; // move the shorter wall: it limits the area
}
return best;
}def max_area(h):
l, r, best = 0, len(h) - 1, 0
while l < r:
best = max(best, min(h[l], h[r]) * (r - l))
if h[l] < h[r]:
l += 1 # the shorter wall limits the area
else:
r -= 1
return bestfunction maxArea(h: number[]): number {
let l = 0, r = h.length - 1, best = 0;
while (l < r) {
best = Math.max(best, Math.min(h[l], h[r]) * (r - l));
if (h[l] < h[r]) l++; else r--;
}
return best;
}- Valid Palindromeends inward, skip non-alphanumericseasy
- Two Sum II – Input Array Is Sortedeasy
- Remove Duplicates from Sorted Arrayread/writeeasy
- Move Zeroeseasy
- Squares of a Sorted Arrayfill result from the backeasy
- 3Sumsort + fix onemedium
- 3Sum Closestmedium
- Container With Most Watermove the shorter wallmedium
- Sort Colorsthree pointers (Dutch flag)medium
- 4Summedium
- Trapping Rain Watertrack leftMax/rightMaxhard
- Opposite-end pointers on sorted data: each move discards impossible candidates → O(n).
- Read/write pointers filter arrays in place with O(1) extra space.
- k-Sum = sort + fix k−2 elements + two pointers: O(n^(k−1)).
- Skip equal neighbours to avoid duplicate results.
QTwo pointers vs hash map for Two Sum — which and when?easy
Unsorted input and indices needed: a hash map, O(n) time and space. Already sorted (or you only need values): two pointers, O(n) time and O(1) space. Sorting first costs O(n log n) and loses original indices.
QTrapping rain water in O(1) space.hard
Two pointers with leftMax and rightMax. Move the side with the smaller max: water above that position is sideMax − height, because the other side is guaranteed to have a taller wall. O(n), O(1).