DEV Community

Victor Joseph
Victor Joseph

Posted on

Remove Duplicates from Sorted Array

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        a = 0
        for i in range(len(nums)):
            if nums.count(nums[a])>1:
                del nums[a]
            else:
                a+=1
Enter fullscreen mode Exit fullscreen mode

So i solved this leetcode problem which can be found here.

My thought process was simple. I initialized a counter variable (called 'a') that would index the entire array (starting from zero) then i looped through the array while counting each variable. I then check if the count of the variable is greater than 1. If yes, then i delete that particular variable and if no, then i increment the counter variable to move to the next index.
At the end of the day, what is left are numbers whose count are equal to 1.

Hope you enjoyed reading, bye :)

Top comments (2)

Collapse
 
anderspersson profile image
Anders Persson

Looks like Python ?
if so using set is better

a = len(set(nums))
Enter fullscreen mode Exit fullscreen mode

set's only store uniq values, and convert a list to set removes duplicates, witch also is effective on big lists to.

Collapse
 
captainvee profile image
Victor Joseph

Thank you Anders for pointing that out