Removing Duplicates from an Array

Rebecca Rosenberg
2 min readNov 29, 2020

I’ve just begun my LeetCode journey (I’m late to hop on this bandwagon because I don’t like to feel like a follower). As many beginners and job-hunters, I’m starting with the “Top Interview Questions,” and I was already challenged. My former self would take to Google to try and find answers, but I decided to stick with it and fly solo (I’m no chump and I deserve a win!).

I wrote the code just as I thought I should. First, I wrote a for loop to iterate through each index of this sorted array. I was tempted to flex some of my ES6 muscles with a for of loop, but I soon realized that the lack of access to the element’s index would make the next step much more difficult.

I then had to determine whether or not the current element I was iterating over was identical to it’s next. For this reason, I had to use the traditional for loop instead of the for of loop, so to keep track of arrays.

For this conditional, I first attempted an if statement:

If this element is identical to its next neighbor, splice it and continue on.

Or so I thought! The tests worked for the first sixteen cases, but not the rest. After wracking my brain for some minutes, I had an epiphany: the while conditional.

My first language (or, as I like to call it, my training-wheel language) that I learned was Ruby. Ruby is all about the loops: for loops, if loops, while loops, until loops, etc. While (no pun intended) JavaScript also loves its loops, you don’t see the more niche ones used as often as you would in Ruby. The key to solving this problem was to use the while loop. Once I implemented it, all the tests passed!

I was able to arrive at the solution with the help of one of the visualizations that LeetCode provided:

Source: LeetCode

They then go on to explain in more detail:

Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.

The word they emphasized, bypass, is extremely important (no duh, Rebecca, that’s why they bolded it). For me, it was more about how I visualized and talked about moving through the array. It wasn’t a staccato if statement — I didn’t need to stop at every element and check. It was a legato while statement:

WHILE this element is identical to its next neighbor, splice it and continue on.

I really enjoyed this exercise and the hints they gave me. It was great to exercise code and think about it in different (i.e., musical) terms.

--

--