Home > front end >  Leetcode problem: Remove Duplicates from Sorted Array
Leetcode problem: Remove Duplicates from Sorted Array

Time:08-02

Example :

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums 
             being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

My code to solve this problem is

 var removeDuplicates = function(nums) {
 const non_duplicates = [];

for (let i=0;i<=nums.length-1;i  ){
    if(!(non_duplicates.includes(nums[i]))){
        non_duplicates.push(nums[i]);
       
    }
     
}
console.log(non_duplicates)
return non_duplicates.length;

};

That console.log(non_duplicates) displays correct output in stdOut. But when I return non_duplictes it prints empty array in output. And when I return non_duplictes.length it returns some array rather than the length of that array.

Please don't suggest any other method to solve this problem. Just tell what is wrong with this code

You can see that problem here

CodePudding user response:

You're returning the correct value but you are not overwriting the nums array with the non-duplicate values.

I think you need to do 2 things:

  1. modify the nums input array in place
  2. return the number of non-duplicates as the return value of the function

So, after calling your function, the return value would be 5 and the first 5 values in the passed-in array would be 0,1,2,3,4 (the value of the others doesn't matter).

Simplest solution that's compatible with your attempted solution is:

  1. copy the values from non_duplicates into nums
  2. return non_duplicates.length.

Here's a simple example of how to do this:

var removeDuplicates = function (nums) {
  const non_duplicates = [];

  for (let i = 0; i < nums.length; i  ) {
    if (!non_duplicates.includes(nums[i])) {
      non_duplicates.push(nums[i]);
    }
  }

  for (let i = 0; i < non_duplicates.length; i  ) {
    nums[i] = non_duplicates[i];
  }

  return non_duplicates.length;
};

CodePudding user response:

Your solution doesn't modify the array inplace. That's the first problem. A bigger problem is that your algorithm is with O(N^2) time complexity, due to includes call and given that "1 <= nums.length <= 3 * 104" your solution would be incredibly slow if it ever passes the tests.

The goal is to find a linear solution of the problem. One possible solution would be:

var removeDuplicates = function(nums) {
    let j = 0;
    for (let i = 1, len = nums.length; i < len; i  ) {
        if (nums[i] !== nums[j]) {
            nums[  j] = nums[i];
        }
    }
    
    return j   1;    
};
  • Related