Two Pointers
Converging or parallel pointers scan arrays and strings in linear time, replacing nested O(n²) loops with single O(n) sweeps. Most useful when the data is sorted or has a symmetric structure (palindromes, pair sums).
Two-pointer techniques use one or two indices to scan a sequence in linear time. The 'converging' variant has pointers walking inward from both ends until they meet — ideal for sorted arrays, palindromes, and pair-sum problems. The 'parallel' variant has both pointers moving in the same direction at different speeds or with different responsibilities, classically a read-pointer paired with a write-pointer for in-place filtering and compression.
The pattern's power is what it eliminates: many problems that look O(n²) (find every pair satisfying a property) collapse to O(n) once you exploit sortedness or symmetry to advance both pointers monotonically.
When to reach for this pattern
- Input is sorted (or trivially sortable) and you need a pair/triplet with a sum or difference property
- Palindrome or symmetric-structure check
- In-place compaction of an array (remove duplicates, remove a value)
- Merging two sorted sequences
- Comparing the structure of two strings (subsequence check)
Canonical template
// converging two-pointer
int l = 0, r = nums.size() - 1;
while (l < r) {
int sum = nums[l] + nums[r];
if (sum == target) return {l, r};
if (sum < target) ++l;
else --r;
}
// write-pointer (in-place filter)
int w = 0;
for (int x : nums)
if (keep(x)) nums[w++] = x;
return w; C++ · adapt the names and types to your problem.
Common pitfalls
- Using
<=instead of<in the converging loop can compare an element with itself - Forgetting to dedup adjacent equal values when emitting pairs / triplets
- Incrementing both pointers on a match in problems where the count of matches matters
- Treating
r - las the count instead of the gap — off-by-one on inclusive ranges
Related patterns
Problems (27)
- Easy
- Easy
- Medium
- Medium
- Medium
- Medium
- Easy
- Medium
- Easy
- Hard
- Hard
- Hard
- Hard
- Hard
- Hard
- Medium
- Easy
- Easy
- Easy
- Medium
- Easy
- Medium
- Medium
- Medium
- Easy
- Easy
- Easy