26. Remove Duplicates from Sorted Array
Remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Return the number of unique elements in nums
.
Intuition
A number is unique if
nums[i] != nums[i-1]
If its not unique we can overwrite it with the next greater element.
Approach
Start from the beginning with
i=0
&j=0
i
is fast points to current element &j
is slow pointing to the previous element.
Only if the previous pointed element is not equal to the current element we increase
j
.write current value in its place
Complexity
Time complexity : $\text{O}(n)$
we iterate the array only once
Space complexity : $\text{O}(1)$
we do operation in-place, no extra space needed
Code
Alternate Solution
Count the number of places to shift each element
we iterate the array only once
we do operation in-place, no extra space needed
Last updated