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 array is already sorted, so all duplicates are adjacent. We can use this property to efficiently remove duplicates in-place by overwriting them as we iterate through the array.

Approach

We use a two-pointer technique:

Complexity

Code

from typing import List

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

        if n == 0:
            return 0
        
        insert_index = 1  # Position to insert the next unique element
        for i in range(1, n):
            # If current element is not equal to the previous, it's unique
            if nums[i] != nums[i-1]:
                nums[insert_index] = nums[i]  # Place unique element
                insert_index += 1  # Move to next position
        
        return insert_index  # Number of unique elements

Back to Problem Statement