Two PointersTwo Pointers
Two Pointers (Same Direction)
A read pointer scans every element while a write pointer marks the end of the finished prefix, compacting or filtering an array in place in one pass.
1
0
1
1
↑write↑read
2
2
3
3
3
4
3
5
5
6
7
7
7
8
9
9
1/20Remove duplicates in place. a[0] is always unique, so write starts at 1: everything before write is the deduplicated prefix.
write pointerread pointerUnique prefixDuplicate (skipped)
PseudocodeLearn Two Pointers (Same Direction) →
1write = 12for read in 1 .. n-1:3 if a[read] != a[write-1]:4 a[write] = a[read]5 write += 16return write # length of unique prefixVariables
write1
read1
Complexity
best O(n)
avg O(n)
worst O(n)
space O(1)
Speed