By iterating through the array and checking if nums at the current index i is less than nums at i + 1, we can find an index for all unique numbers in the array. We can then insert each of these numbers to the beginning of the array, at addIndexaddIndex starts at 0 as the first element in the array is always unique.

Complexity

  • Time complexity: O(n)

  • Space complexity: O(1)

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length == 0)
            return 0;
        
        int addIndex = 1; //index that unique characters will be inserted at
 
        for(int i = 0; i < nums.length - 1; i++) {
            
            if(nums[i] < nums[i + 1]){ //if true, num[i + 1] is a new unique number
              nums[addIndex] = nums[i + 1];
              addIndex++;
            }
        }
        return addIndex;
    }
}