Remove duplicates from sorted array

August 29, 2022

array-and-hashmap

Problem URL: Remove duplicates from sorted array

We will iterate over each element from index 1 to the end of the list, if 2 consecutive numbers are equals, we convert the first number to 101, as out input list could have numbers upto 100. Then we sort them, and count the number of elements which are not 101, and finally return the count.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        for i in range(1, len(nums)):
            if nums[i-1] == nums[i]:
                nums[i-1] = 101
        nums.sort()

        count = 0
        for n in nums:
            if n != 101:
                count += 1
        return count

Time Complexity: O(nlog(n))
Space Complexity: O(1)

We can also do it with python magic by using set and list functions.

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