We are in Beta and we are offering 50% off! Use code BETATESTER at checkout.
You can access a significantly larger sample of the platform's content for free by logging in with your Gmail account. Sign in now to explore.

Remove duplicates in place (leetcode 26)

Data Structures and Algorithms Easy Seen in real interview

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. Return k.s.

Examples:

  • Input: nums = [1,1,2], Output: 2. The resulting nums will look lie: nums = [1,2,_]
  • Input: nums = [0,0,1,1,1,2,2,3,3,4], Output: 5. The resulting nums will look lie: nums = [0,1,2,3,4,_,_,_,_,_]
One way to solve this problem is to use two pointers, a left and a right one. The left shows the end of the non-duplicated array (i.e., the result). The right shows the current element of the matrix. As we move the right index, we check whether it is the same as the left one. If it is, then it means we have a duplicate, and we can ignore that element: hence we can move the right index to the right. If not, then we have a new element, and hence we can copy the right element to the \(left+1\) place in the array, and move on to the next elemnt.


class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # use two pointers: left and right. 
        # the left tracks the non-duplicated array; the right tracks how many elements 
        # we have seen so far.
        l,r = 0,1
        n = len(nums)
        while r < n:
            if nums[r] == nums[l]:
                # duplicate, move right index
                r+=1
            else:
                l+=1
                # replace the next element in nums[l] w the current in nums[r]
                nums[l] = nums[r]
                r+=1
        return l+1

If we wanted to run it on an example:

s = Solution()
nums = [0,0,1,1,1,2,2,3,3,4]
i = s.removeDuplicates(nums)
nums[:i]
## [0, 1, 2, 3, 4]


The time complexity of this solution is \(O(N)\), since there is no nested loop.


Topics

Array, Two pointers
Similar questions

Provide feedback