Fast Simple 5 Line Python O(n) time O(1) space solution with comments

  • 0

    The idea here is to move from left to right in array and swapping elements that are duplicates out with elements we find that are not duplicates. If nums[i] and end[i+1] are not equal then we just swap the new element with the first found duplicate (and if there are no duplicates we essentially swap the element with itself for no impact). By the time we reach end of array all the duplicates have been swapped to the back end of array.

     def removeDuplicates(self, nums):
        end = 0
        for i in range(1, len(nums)):
            if nums[i] != nums[end]:
                nums[end+1], nums[i], end = nums[i], nums[end+1], end + 1
        return end+1 if nums else 0

  • 1

    nums[end+1],end = nums[i],end + 1

    This is enough. we don't need to sign nums[i] = nums[end+1]

  • 0

    You, my friend, are correct

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.