Leetcode: Remove Duplicates from Sorted Array II(80)

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

Ayush Tibra
The Tech Bible
2 min readFeb 28, 2024

--

Day 4:

Photo by Pankaj Patel on Unsplash

So, the problem I chose to start for the fourth 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,1,2,3,3]

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

Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3, and 3 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Code:

Solution 1:

const arrayLength = nums.length;
let trackCountElement = countOccurence(nums);

let p1 = 0;
for (let i = 0; i < arrayLength; i++) {
if (trackCountElement[nums[p1]] > 2) {
nums.splice(p1, 1);
trackCountElement = countOccurence(nums);
} else {
p1++;
}
}

function countOccurence(arr) {
const trackCountElement = {};
for (let i = 0; i < arr.length; i++) {
if (!trackCountElement[arr[i]]) {
trackCountElement[arr[i]] = 1
} else {
trackCountElement[arr[i]]++
}
}
return trackCountElement;
}

Solution 2:

 let c = 0;

for (let i = 0; i < nums.length; i++) {
if (nums[i] !== nums[i + 2]) {
nums[c] = nums[i];
c++
}
}

return c;

So, I’ll explain solution 1 as solution 2 is self-explanatory:-

  • We create a function named countOccurence, which will return the occurrence of each element in the array.
  • Then we’ll loop through our array and check which element has an occurrence in the array more than 2.
  • If there is an element that has an occurrence of more than 2 then we delete that element using the splice function and again track the occurrence of each element in the new array.
  • If not greater than 2, then we increase the variable p1.

It’s a long way to solve it, but that is my first solution and when I solved this problem again I solved it using Solution 2.

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 :)

--

--