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:
|
|
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 incrementj
. - After scanning all elements in
nums
,j
will be the length of the array without excessive duplicates. So we returnj
.
This solution works in-place and uses O(1) extra space, as required by the problem.