Home > Software design >  Remove Duplicates from Sorted Array - Why is my python code wrong?
Remove Duplicates from Sorted Array - Why is my python code wrong?

Time:01-02

This is a question from Leetcode. Given this sorted array nums = [0,0,1,1,1,2,2,3,3,4]

I want the output to be nums = [0,1,2,3,4]

However my code...

    low = nums[0] - 1
    
    for num in nums:
        if num == low:
            nums.remove(num)
        else:
            low = num
    
    print(nums)        

...produced this output: [0,1,1,2,2,3,4]

Can anyone please shed some light on where the error is?

CodePudding user response:

You're removing from the array while iterating over it. That can cause problems, as the memory in the list is shifting as you're accessing it.

Here's a one-liner:

# set() removes duplicates.
# We need to call sorted() on the set, as sets don't preserve insertion order (thanks Kelly Bundy!)
return sorted(set(nums)) 

Edit: Apparently, LeetCode asks for solutions that use O(1) memory. Here’s an alternate solution that meets the constraints of the original problem.

They also ask for a bunch of other weird quirks in the solution, so if you think something's off, read the problem statement before commenting or voting.

This solution works by keeping track of an index to insert new elements and the last element we've seen -- if we see a new element, we add it at the insertion index and increment our insertion index by one.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if not nums:
            return 0
        insertion_index = 1
        previous_number = nums[0]
        for i in range(1, len(nums)):
            if nums[i] != previous_number:
                nums[insertion_index] = previous_number = nums[i]
                insertion_index  = 1
        return insertion_index

CodePudding user response:

The issue lies in the fact you are removing elements from the array you are looping through.

After the 0 at index 1 is removed (during the second iteration of the loop), the next value of num will be the second 1, at index 2 of the nums list (after removing the 0), which is at index 3 initially.

Instead the easiest thing to do is to loop through the indices of the list in reverse, and use this method to get the current num and use the same content of the loop you already use.

Edit: Typo

CodePudding user response:

You can use set as follows:

new_list = list(set(nums))
  • Related