SDE & MLE Prep

80. Remove Duplicates from Sorted Array II

Problem

nums is sorted. Remove duplicates in place so each value appears at most twice, keeping the order, and return the new length k.

Example: [0,0,1,1,1,1,2,3,3] → 7, with nums starting [0,0,1,1,2,3,3]

Constraints: O(1) extra space.

Allow at most two copies: keep x if k < 2 or x != nums[k-2] (compare with the element two slots back in the kept prefix).

Complexity: O(n).

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 0
        for x in nums:
            if k < 2 or x != nums[k - 2]:
                nums[k] = x
                k += 1
        return k