Leetcode: Remove Duplicates from Sorted Array (26)

Problem no. 26 (Remove Duplicates from Sorted Array) using JavaScript.

Ayush Tibra
The Tech Bible
2 min readFeb 27, 2024

--

Day 3:

Photo by Pankaj Patel on Unsplash

So, the problem I chose to start for the third day is the Array problem in the Leetcode Top Interview 150 series.

I will solve all the problems only in JavaScript, I know most people use C++, Java, or Python to solve DSA problems, but why not try something different!

Let’s start:
The problem states that:

Example 1:

Input:
nums = [0,0,1,1,1,2,2,3,3,4]

Output:
k = 5, nums = [0,1,2,3,4,_,_,_]

Code:

    let p1 = 0;
let p2 = 1;
while (p1 < nums.length) {
if (nums[p1] == nums[p2]) {
nums.splice(p1, 1);
} else {
p1++;
p2++;
}
}
return nums.length;

So, I’ll explain the solution, we create two variables to point out the indexes of the array, and we are always comparing the first and second index of an array, if they are the same means duplicate then we can remove that element. If not then we are increasing the variable p1, and p2 values to compare the next element and so on.

It’s a self-explanatory solution for all of you as I only used basic JavaScript functions. If anyone has doubts, please let me know in the comment section.

Please share your views in the comment section and yeah feedback is appreciated.
Hoping you would like and will share this for better reach.
Checkout my other articles on — https://medium.com/@aayushtibra1997
Thanks for reading :)

--

--