Solving Remove Duplicates from Sorted Array in JavaScript!

Today, we’re going to be solving Leetcode’s Problem #26, Remove Duplicates from Sorted Array.

The Problem Statement:

This is asking for a lot!

Let’s break down what it’s asking for:

  • We are given an array called nums, which is randomly sorted.
  • We need to remove the duplicate numbers without creating another array (that’s what the in-place part is asking for).
  • We then need to return the number of unique items (k) in the array

Here are the examples they provide:

To begin doing this, we’re going to create pointers that reference whatever element we’re on in the array and compare them to each other.

The first pointer will begin with the first element in the nums array.

Our second pointer will need to increment throughout the nums array, so we should put it in our for loop so that we can compare the elements.

Pointer2 needs to start at 1 so that it can be compared to the first pointer (0) which is the first element.

If this is confusing, think of the index numbers.

Indices do not start at 1, they start at 0.

Now, we will compare the two numbers to each other.

If the number that pointer1 is at doesn’t equal the number pointer2 is at, we’ll want pointer1 to move to the next number.

Then, we want to replace the number pointer1 is at with the number pointer2 is at.

Now, the loop will continue until they reach the end of the array.

The last thing we have to do is look at the index of whatever pointer1 has settled on.

But, we need to add a +1 to represent how many unique items there are in the array since pointer1 stops right before the end of the array (because pointer2 is there!)

✨✨✨And that’s it!




MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tish Faroul

MHA grad & Software Engineer | Rails | React | JavaScript | CSS | HTML