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.

Learn Two Pointers (Same Direction) →
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)
1write = 1
2for read in 1 .. n-1:
3 if a[read] != a[write-1]:
4 a[write] = a[read]
5 write += 1
6return write # length of unique prefix
Variables
write1
read1
Complexity
best O(n)
avg O(n)
worst O(n)
space O(1)
Speed