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.

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

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

Space Complexity
Time Complexity

O(1)\text{O}(1)

O(n)\text{O}(n)

  • we iterate the array only once

  • we do operation in-place, no extra space needed

Last updated