Leetcode - Remove Duplicates from Sorted Array (with JavaScript)
Urfan Guliyev
Posted on May 30, 2020
Today I am going to show how to solve the Leetcode Remove Duplicates from Sorted Array algorithm problem.
I take the first element (let i = 0) of a sorted array and compare it to the next elements. If the next element is a duplicate, it will be skipped.
If the next element is not a duplicate, I will copy its value to the element at the index i+1.
I could’ve created a new array and pushed elements there. But as required in the problem, I have to modify the existing array instead.
I repeat the same process again until the loop reaches the end of the array. The function then returns the length of the array.
var removeDuplicates = function(nums) {
if(nums.length == 0) return 0;
let i = 0;
for (let j = 1; j < nums.length; j ++){
if(nums[j] !== nums[i]){
i++;
nums[i] = nums[j];
}
}
return i + 1
};
💖 💪 🙅 🚩
Urfan Guliyev
Posted on May 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.