LeetCode problem #26 — Remove Duplicates from Sorted Array (JavaScript)

Duncan McArdle
1 min readDec 16, 2020

--

In this LeetCode problem, we’re provided with an array of numbers, and asked to remove any duplicates, without creating a new array. In other words, the original array must be manipulated in-place, rather than just moving the unique values to a new array and returning that.

Solution #1: The loop

More or less all solutions to this problem revolve around the same basic concept: You loop through the array, move all the unique numbers to the front, and then chop off the tail. So that’s what we’ll do here:

Throughout the loop we maintain a “unique cursor”. This cursor tracks how many unique values have been found, and thus allows us to know where to place the next unique value in the original array.

You’ll notice that the end of this solution is a little odd, and that’s because of how LeetCode grade the submissions. They don’t penalise you for not chopping off the tail, so I’ve commented it out in order to boost performance. In addition, rather than returning the modified array, for some reason the return value has to be the number of unique elements, so that’s what we’re returning here.

--

--

Duncan McArdle
Duncan McArdle

Written by Duncan McArdle

Full-stack software developer from the UK, author of the Aftermath book series, full time tech-nerd.

No responses yet