DEV Community

Nathan Kurz
Nathan Kurz

Posted on

3 2

LeetCode 26: Remove Duplicates from Sorted Array

Let's talk about removing duplicates. Normally, removing duplicates from a sorted array would be quick work. You just add each value to a set. Since all values in sets must be unique you simply return the values contained in the set. This was not a valid solution for this problem.

The problem states that you have to modify the array in place. That means I can't create another data structure to store my values when I find any duplicates. Admittedly, the solution is still straightforward. I have not had the pleasure of using the splice() function in JavaScript too many times, so it took me a bit longer than I would have liked until I rediscovered it.

Now we will build the solution. I'll explain it first with some pseudocode, and then present the actual code below.

  • Loop through the array
  • The array size will change when we remove an element, so we need to use a variable to store the initial array length
  • check if i is greater than or equal to array.length
  • break if true
  • check if i equals i+1
  • if true, remove element at index i with splice()
  • decrement i to recheck that same position in case of further duplicates

Like I said, pretty straightforward. I tend to overthink these algorithm problems. That's why I'm practicing!

Solution:

var removeDuplicates = function(nums) {
    let numsLength = nums.length;
    for (let i = 0; i < numsLength; i++) {
        if (i >= nums.length) {
            break;
        }
        if (nums[i] === nums[i + 1]) {
            nums.splice(i, 1);
            i--;
        }
    }
};
Enter fullscreen mode Exit fullscreen mode

Hope you learned something!! Have a great day and remember to GO OUTSIDE :)

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay