80. Remove Duplicates from Sorted Array II

Remove the duplicates in-place such that each unique element appears atmost twice. The relative order of the elements should be kept the same.

Input: nums = [1,1,2,2,2,2,2,3,3,3,3,3]
Output: 2, nums = [1,1,2,2,3,3]

Return the number of unique elements in nums.

Do not allocate extra space for another array. Achieve this by modifying the input array in-place with $\text{O}(1)$ extra memory.

Intuition

  • We can move an element forward by the amount of duplicates before it.

Approach

  • We track the occurrence of an element.

  • Start moving the next elements forward only if the current elements occurrence is greater 2.

Complexity

  • Time complexity : $\text{O}(n)$

    • We iterate the array only once

  • Space complexity : $\text{O}(1)$

    • We use no extra space, do operations in-place

Code

Another Way

Last updated