Leetcode 80: Remove Duplicates II

Leetcode 80 asks us to modify a sorted array so that each unique element appears at most twice. We are to preserve relative order and store the result in the first part of array nums. The first k elements of nums will hold the result, and beyond k it does not matter what values may have been left behind. Lastly, this must be accomplished by modifying the input array in-place, without allocating any extra space.

I chose to do a writeup on this problem because it's the first time I've run into the possibility that there really isn't a feasible naive approach that respects all of the restrictions put in place - namely, the requirement of modifying in-place. I tried using splice() to shift elements out of the array while tracking position with a single pointer. However, using splice() and subsequently having to decrement the pointer with i-- doesn't work in the case of three or more consecutive duplicates. It will skip a value for the same reason outlined in Day 2. There was an identical issue I ran into there, and it is explained here Day 2 Remove Element. It may not be worth the time to continue digging around, but I am curious whether there does exist a naive approach that respects the restrictions completely.