Inplace Remove Duplicate Values in an Array

Solution-1

class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ from collections import defaultdict myDict = defaultdict(int) searchIdx = 0 fillIdx = 0 for searchIdx in range(len(nums)): if myDict[nums[searchIdx]]>0: # this is dup pass else: myDict[nums[searchIdx]] = 1 nums[fillIdx] = nums[searchIdx] fillIdx += 1 return fillIdx

Solution-2

class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ # now using the idea that the array is sorted # we do not need to use the defaultDict # let us handle the case when the array is empty if not nums: return nums # let us start from idx 1 and search through the array # .. duplicate items in a sorted array are place consecutively # .. we will compate idx and one place before that to see duplicates fillIdx = 1 for searchIdx in range(1,len(nums)): if nums[searchIdx]!=nums[searchIdx-1]: nums[fillIdx] = nums[searchIdx] fillIdx += 1 return fillIdx