Remove Duplicates from Sorted Array II

This can be solved using a two-pointer technique. Let’s name our pointers i and j. The i pointer will be used to iterate through nums, while j will mark the position where the next element should be placed.

We will keep a count of the current number’s frequency. If the count is less than or equal to 2, we place the number in the j-th position and increment j. Finally, we return j as the length of the array after removal of duplicates.

Here is the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        j, count = 1, 1

        for i in range(1, len(nums)):
            if nums[i] == nums[i - 1]:
                count += 1
            else:
                count = 1

            if count <= 2:
                nums[j] = nums[i]
                j += 1

        return j

This code does the following:

  • It starts from the second element of nums (i.e., nums[1]), comparing each element with its previous one.
  • If the current element is the same as the previous one, increment the count.
  • If it’s a new element, reset the count to 1.
  • If the count is less than or equal to 2, place the current element to the position marked by j and then increment j.
  • After scanning all elements in nums, j will be the length of the array without excessive duplicates. So we return j.

This solution works in-place and uses O(1) extra space, as required by the problem.