0

Why does my solution work in the console but not on leetcode?

var removeDuplicates = function(nums) {
    let res = [];     
    for(let num of nums) {
        if(res.includes(num) === false) {
            res.push(num);
        }
    }   
    return res.length;
};

Console: screenshot

Leetcode:

let arr = [1, 1, 2]

removeDuplicates(arr) // 3 
1
  • have you tried using If(res.indexOf(num) < 0) ? instead of if(res.includes(num) === false) Commented Nov 22, 2018 at 7:01

3 Answers 3

2

You can try changing includes to indexOf, may be includes is not working in your environment. Also, instead of returning length you should return res.

Just in case you want to try another approach, you can look at Sets like below

var removeDuplicates = function(nums) {
    return [...new Set(nums)]
};

console.log(removeDuplicates([1,1,2]))

console.log(removeDuplicates([1,1,2,3]))

Sign up to request clarification or add additional context in comments.

5 Comments

Yes @YosvelQuintero just realised that. :)
Sets can take arrays of inputs directly
Edited. Thank you @YosvelQuintero.
Good to help.. Removing my answer because yours was first
That's so kind of you @YosvelQuintero. That's why I love SO, people are so willing to promote fellow learners. Thank you :)
0

You don't use sortness properly. Algorithmically it is more effective to compare item with previous one, so complexity is O(N).

Perhaps JS has some high-order function like Python groupby to make shorter code, but described method is definitely the best possible from algorithmical point of view.

ideone

var removeDuplicates = function(nums) {
    let res = []; 
    let last = NaN
    for(i=0; i<nums.length; i++) {
        if(nums[i] != last) {
            res.push(nums[i]);
            last = nums[i];
        }
    }   
    return res.length;
};

let arr = [1, 1, 2]
print(removeDuplicates(arr)) 

>>2

Comments

0

Here is another solution you can try...

var removeDuplicates = function(nums) {
  let p1 = 0,lastVal =nums[0] -1;
  for (let i = 0; i < nums.length; i++) {
   if (nums[i] != lastVal) {
    nums[p1] = nums[i];
    lastVal = nums[i]
    p1 +=1;
  }
 }
nums.length = p1;
console.log(nums);
};

let arr = [1, 1, 2]
removeDuplicates(arr);

Click here to RUN

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.