What is Remove Duplicates
The array is sorted. Compact it so the unique values form a prefix, and return how many unique values there are. A slow pointer writes the next new value. A fast pointer scans forward. The practice tests ask only for that count.
1 1 2 2
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is read once. |
| Memory | O(1) | The unique values overwrite the front of the same array. |
Implementation
def unique_count(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