visual walkthrough
Remove Duplicates from Sorted Array II
Generalises read/write pointers to 'keep at most k copies'.
The idea
It's the same read/write idea as the one-copy version, with one change: a value is a third copy exactly when it equals the value two places behind `write`.
In a sorted array that single comparison is enough.
Complexity
| approach | time | space |
|---|---|---|
| Count each value | O(n) | O(n) |
| Read / write pointers | O(n) | O(1) |