I'm working on a Leet code challenge where I'm trying to remove all duplicates from a sorted ascending array of integers.
So for example [1,1,1,2,2,3,4,5,5,5] should return [1,2,3,4,5].
I have solved this one way, but was trying a different way as per the code below, but it seems to always return an empty array [].
Could anyone point me in the direction (of what might be very obvious but I havent seen it) of why this always returns an empty array?
var removeDuplicates = function(nums) {
for(let i = 0; i < nums.length; i++) {
let counter = 0;
for(let x = i + 1; x < nums.length; x++) {
// Remove element if above is true
if(nums[i] == nums[x]) {
counter++;
}
}
nums.splice(i + 1, counter);
}
return nums;
};
console.log(removeDuplicates( [1,1,1,2,2,3,4,5,5,5] ));
You will get an empty array, because your algorithm is wrong. Your algorithm will works correctly just when the similar numbers are side by side each other. For example:
[1,1,1,2,2,5,5,5,5,5,3,3]
Otherwise it doesn't work correctly.
There are lots of algorithm to remove duplicated values from an array. Please have a simple search to find them. But you can easily remove duplicate values in an array in these ways:
function removeDuplicates(numbers) {
return [...new Set(numbers)];
}
Or:
function removeDuplicates(numbers) {
return numbers.filter((num, index, self) => index === self.indexOf(num));
}