loading...

Leetcode - Remove Duplicates from Sorted Array (with JavaScript)

urfan profile image Urfan Guliyev Updated on ・1 min read

Today I am going to show how to solve the Leetcode Remove Duplicates from Sorted Array algorithm problem.

Here is the problem:
Alt Text

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
};

Posted on by:

urfan profile

Urfan Guliyev

@urfan

Love coding, eating and travelling

Discussion

markdown guide