Remove Duplicates from Sorted Array II – Python 3 ( Week 11 – 07)

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        
        if len(nums) <= 1:
            return 1 
        
        index, ans, first = 0, 0, 0
        
        while first < len(nums):
            i = 1
            while first + i < len(nums) and nums[first] == nums[first + i]:
                i += 1
                
            if i == 1:
                nums[index] = nums[first]
                ans = index
                index += 1
                first += 1
            else:
                nums[index] = nums[first]
                nums[index + 1] = nums[first]
                ans = index + 1
                index += 2
                first += i
            
        return ans + 1
            
            
            
    

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started