O(n) Java solution with better variable names

  • 0

    The idea: Loop through the list and replace the nums array with unique values in the order you see them. Everytime you replace the nums array, you need to make sure you increment the sortedIndex.

    Psuedo code:

    loop through list
      is the current element a dupe? 
          ignore it
          add to growing list of unique values by replacing the next replacable
          index in nums

    The code:

        public int removeDuplicates(int[] nums) {
            int prevIndex = -1;
            int currIndex = 0;
            int sortIndex = -1;
            while (currIndex < nums.length) {
                if (prevIndex == -1 || nums[currIndex] != nums[prevIndex]) {
                    nums[sortIndex] = nums[currIndex];
            return sortIndex + 1;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.