#I4G10DaysOfCodeChallenge - Day 1

Remove Duplicates from Sorted Array

Question

Attempting the LeetCode problem 26. Remove Duplicates from Sorted Array

This particular problem requires that you remove duplicates from an array in-place. The problem can be approached in several ways but I'd highlight two of those, the short easy way, and the rather long way. Let's get to it.

Method 1 (Using a loop)

Using a loop is probably the first thing that comes to mind when it comes to array manipulation. What this method just does is iterate through the array and remove it if it still has another occurrence in the array. Let's go through the code:

def removeDuplicates(nums: list[int]) -> int:
    # set a counter and initialize a while loop
    i = 0
    while i < len(nums):
        # check if the item being checked occurs more
        # than once then remove it from the list
        if nums.count(nums[i]) > 1:
            del (nums[i])
        else:
            i += 1
    return len(nums)

Method 2 (Using sets)

Leveraging the core attributes of "sets" which is element uniqueness ie, sets do not allow duplicates, but it should be put into consideration that sets do not keep track of the order of elements, so, sorting will still be necessary to make this a valid solution. Now to the code:

def removeDuplicates(self, nums: list[int]) -> int:
        # convert the list to a set, and assign the value to the array
        nums[:] = set(nums)
        # sort the array (in ascending order by default)
        nums.sort()
        return len(nums)

For me, I think using sets is faster and easier to understand than going through the loop. The choice is yours, so go ahead and keep bouncing. Happy coding!

Kindly follow me on Twitter || LinkedIn