Peeush Agarwal > Engineer. Learner. Builder.

I am a Machine Learning Engineer passionate about creating practical AI solutions using Machine Learning, NLP, Computer Vision, and Azure technologies. This space is where I document my projects, experiments, and insights as I grow in the world of data science.

View on GitHub

Intuition

The problem asks us to remove duplicates from a sorted array such that each unique element appears at most twice. Since the array is sorted, duplicates are adjacent, making it easy to count occurrences as we iterate.

Approach

We use two pointers:

For each element:

This ensures that each unique element appears at most twice, and the order is preserved.

Complexity

Code

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 0:
            return 0

        insert_index = 1
        count = 1
        for i in range(1, n):
            if nums[i] == nums[i-1]:
                count += 1
                if count > 2:
                    continue
            else:
                count = 1
            nums[insert_index] = nums[i]
            insert_index += 1
        return insert_index

Back to Problem Statement