Remove Duplicates from Sorted Array

Problem Id: 26 Difficulty: Easy Tag: Array Tag: Two Pointers


Intuition

This is a simple problem. We could use 2 indexes and an additional variable prev. The first index is to use to mark which number is been read now. And the second index is to mark the position to write the value to. Since there would always read before write, we don't need to consider if i1 is equal to i2.

Solution


class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        prev = None
        i2 = 0
        for i1 in range(len(nums)):
            if nums[i1] != prev:
                prev = nums[i2] = nums[i1]
                i2 += 1
        return i2