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]
So my code
low = nums[0] - 1
for num in nums:
if num == low:
nums.remove(num)
else:
low = num
print(nums)
However my code produced this output: [0,1,1,2,2,3,4]
Can anyone please shed some light on where the error is?
>Solution :
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. 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