Skip to content

visual walkthrough

Remove Duplicates from Sorted Array II

MediumSame Direction (Read/Write)Reported at: Adobe

Generalises read/write pointers to 'keep at most k copies'.

Solve on LeetCode

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

approachtimespace
Count each valueO(n)O(n)
Read / write pointersO(n)O(1)

More walkthroughs