Remove Duplicates from Sorted Array II

Problem Id: 80 Difficulty: Medium Tag: Array Tag: Two Pointers


Intuition

This could be solved by one-pass solution. Notice that, for each node, we need to visit it before we change it.

Solution


class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        prev, prev_count = None, 0
        hi = 0
        for num in nums:
            if num != prev:
                nums[hi] = num
                hi += 1
                prev = num
                prev_count = 1
            elif prev_count == 1:
                nums[hi] = num
                hi += 1
                prev_count += 1
            else:
                pass
        return hi