Arrays & Hashing · Pattern 5 of 26
Two pointers
Two indexes that only move forward (or toward each other), so the whole scan is O(n). Opposite ends for sorted pairs and palindromes; a read and a write pointer for in-place edits; one pointer per sequence for comparing.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- A sorted array and a pair condition
- Palindromes, reversing, or comparing from both ends
- Remove or move elements in place with O(1) extra space
- Walk two strings or arrays side by side
The template
// opposite ends: is there a pair with this sum? (sorted input)
boolean hasPairWithSum(int[] a, int target) {
int i = 0, j = a.length - 1;
while (i < j) {
int s = a[i] + a[j];
if (s == target) return true;
if (s < target) i++; // need a bigger sum
else j--; // need a smaller sum
}
return false;
}
// read / write pointers: remove duplicates from a sorted array in place
int removeDuplicates(int[] a) {
int w = 0; // a[0..w) is the answer so far
for (int r = 0; r < a.length; r++)
if (w == 0 || a[r] != a[w - 1]) a[w++] = a[r];
return w;
} def has_pair_with_sum(a, target): # opposite ends, sorted input
i, j = 0, len(a) - 1
while i < j:
s = a[i] + a[j]
if s == target:
return True
if s < target:
i += 1 # need a bigger sum
else:
j -= 1 # need a smaller sum
return False
def remove_duplicates(a): # read / write pointers, in place
w = 0 # a[:w] is the answer so far
for r in range(len(a)):
if w == 0 or a[r] != a[w - 1]:
a[w] = a[r]
w += 1
return w // opposite ends: is there a pair with this sum? (sorted input)
bool hasPairWithSum(vector<int>& a, int target) {
int i = 0, j = (int)a.size() - 1;
while (i < j) {
int s = a[i] + a[j];
if (s == target) return true;
if (s < target) i++; // need a bigger sum
else j--; // need a smaller sum
}
return false;
}
// read / write pointers: remove duplicates from a sorted array in place
int removeDuplicates(vector<int>& a) {
int w = 0; // a[0..w) is the answer so far
for (int r = 0; r < (int)a.size(); r++)
if (w == 0 || a[r] != a[w - 1]) a[w++] = a[r];
return w;
} // opposite ends: is there a pair with this sum? (sorted input)
function hasPairWithSum(a, target) {
let i = 0, j = a.length - 1;
while (i < j) {
const s = a[i] + a[j];
if (s === target) return true;
if (s < target) i++; // need a bigger sum
else j--; // need a smaller sum
}
return false;
}
// read / write pointers: remove duplicates from a sorted array in place
function removeDuplicates(a) {
let w = 0; // a[0..w) is the answer so far
for (let r = 0; r < a.length; r++)
if (w === 0 || a[r] !== a[w - 1]) a[w++] = a[r];
return w;
} The variations
-
1Opposite ends on sorted data
Start at both ends. The sum (or area, or weight) tells you which side to move: the move that cannot be part of a better answer. Sort first when the order of the answer does not matter.
Now you solve- Valid Triangle Number Medium Stuck? ▶ video
- Container With Most Water Medium Stuck? solution
- Trapping Rain Water Hard Stuck? solution
- Boats to Save People Medium Stuck? solution
- 4Sum Medium Stuck? solution
- Divide Players Into Teams of Equal Skill Medium Stuck? solution
- Squares of a Sorted Array Easy Stuck? solution
- Sort Transformed Array Medium Stuck? solution
-
2Palindromes and reversing
Compare or swap from both ends, moving inward. Skip characters that do not count; allow one mismatch by trying both skips.
Now you solve -
3Read and write pointers (in place)
The read pointer scans everything; the write pointer marks where the next kept element goes. Everything before the write pointer is the answer so far.
Now you solve -
4One pointer per sequence
Walk two strings or arrays together, advancing whichever pointer the comparison allows. Subsequences, typed-with-long-press and abbreviations all work this way.
Now you solve- Backspace String Compare Easy Stuck? solution
- Long Pressed Name Easy Stuck? solution
- Expressive Words Medium Stuck? solution
- Valid Word Abbreviation Easy Stuck? solution
- One Edit Distance Medium Stuck? solution
- Intersection of Two Arrays Easy Stuck? solution
- Shortest Word Distance Easy Stuck? solution
-
5Walk runs: up, down, gaps
Move a pointer while a condition holds (going up, same value, empty seat), then measure the run. Mountains, ranges and gaps between people are runs.
Now you solve -
6More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Using opposite-end pointers on an unsorted array: the "move the smaller side" logic only works when the order means something.
- Moving both pointers when only one should move.
- For merge-in-place problems, writing from the front and overwriting values you still need. Write from the back.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.