0026. Remove Duplicates from Sorted Array

Easy | Two Pointer | 72 ms (97.82%), 15.6 MB (96.43%)

Source: LeetCode - Remove Duplicates from Sorted Array GitHub: Solution / Performance

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.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Use two pointers, one for iterating and the other one for placing.

  • If the place-pointer is at the index 0 (very first beginning), we place the number and move the place-pointer. placeP += 1

  • Besides, if the current number is different from the previous element pointed by place-pointer nums[moveP] != num[placeP = 1], we also place the number nums[placeP] = nums[moveP] and move the place-pointer.

  • Otherwise, we increase move-pointer's index. moveP += 1

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        # (base case)
        if len(nums) == 0 or len(nums) == 1: return len(nums)
        
        # ==================================================
        #  Array + Two Pointer                             =
        # ==================================================
        # time  : O(n)
        # space : O(1)
        
        moveP, placeP = 0, 0
        
        while moveP < len(nums):
            # meet number different from previous placed number
            if placeP == 0 or nums[moveP] != nums[placeP - 1]:
                nums[placeP] = nums[moveP]
                placeP += 1
                
            moveP += 1
        
        return placeP

Last updated