DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

1 1

Leetcode - 26. Remove Duplicates from Sorted Array

There are multiple ways to solve this but we need to solve it in inplace as mentioned in the problem

otherwise
we can have a new array, and use the Set trick

Trick is to know if a number is duplicate (seeing that num for first time) in a sorted array we just need to compare with the previous element

one point l -> takes care where u r going to update
other pointer r -> takes care of going through all numbers

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {

    let l = 1 ;
    for ( let r = 1 ; r<nums.length;r++){
            if( nums[r] != nums[r-1]){
                nums[l] = nums[r];
                l++
            }
    }
    return l
};
Enter fullscreen mode Exit fullscreen mode

please leave your ideas or suggestions in the comments ☺️

Top comments (2)

Collapse
 
gesslar profile image
gesslar

It would be helpful to mention that this is an in-place mutation. For a new array, the Set trick is pretty good. It is lovely, though.

Collapse
 
rakeshreddy512 profile image
Rakesh Reddy Peddamallu

thank you for suggestion 😁 , i will update the post

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up