26. Remove Duplicates from Sorted Array
CPU: O(n)
Memory: O(1)
from typing import List

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i = 0

        for index in range(1, len(nums)):
            if nums[i] != nums[index]:
                nums[i+1] = nums[index]
                i += 1
        
        nums = nums[:i+1]
        
        return len(nums)

def main():
    s = Solution()

    print(s.removeDuplicates([1,1,2])) # 2
    print(s.removeDuplicates([0,0,1,1,1,2,2,3,3,4])) # 5

if __name__ == '__main__':
    main()
			
  • Not able to pass the leetcode test, memory complexity is not O(1)
  • from typing import List
    
    class Solution:
        def removeDuplicates(self, nums: List[int]) -> int:
            return len(sorted(list(set(nums))))
    
    def main():
        s = Solution()
    
        print(s.removeDuplicates([1,1,2])) # 2
        print(s.removeDuplicates([0,0,1,1,1,2,2,3,3,4])) # 5
    
    if __name__ == '__main__':
        main()