Home:ALL Converter>Remove Duplicates from Sorted Array in O(1) Space

Remove Duplicates from Sorted Array in O(1) Space

Ask Time:2022-10-16T00:30:02         Author:Rhodey

Json Formatter

Question: https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

Basically, duplicates in a sorted array needs to be removed without creating a new one. I have tested my solution, and it falters when there are 3, 5, 7 (and so on) number of duplicates of the same number. What techniques can I try?

Code:

def removeDuplicates(nums):
    i = 0 # moving pointer
    end = len(nums)-1 # points to the end of the array
    # iterates over the array
    while i != end:
        # if current number is equal to the next
        if (nums[i] == nums[i+1]):
            # pop it off
            nums.pop(i)
            # decrement the length of array
            end -= 1
        i += 1 # increments the moving pointer
    return i + 1


nums = [0,0,1,1,1,2,2,3,3,4]
print(removeDuplicates(nums))

Author:Rhodey,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74081194/remove-duplicates-from-sorted-array-in-o1-space
yy