DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on • Edited on

9 2

Leetcode - Remove Duplicates from Sorted Array (with JavaScript)

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


Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay