LeetCode: Remove Duplicates from Sorted List

Melissa Guachun
2 min readDec 16, 2021
Photo by Waldemar Brandt on Unsplash

Another day, another LeetCode problem! From the get-go the task at hand is to take a head of the sorted list and return the list without any duplicates.

To help us, we can look at the notes given with the problem:

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/

A linked list consists of nodes where each node has a value property. The property .val is used to help us assess the property value of a node. The.next property points to the next node in the linked list. Looking at the input, we are given a head of a sorted list. Head is going to reference the starting current value of the list, so we make the variable current equal to head. Immediately we know we can use .val and .next as properties to help us build our algorithm.

var deleteDuplicates = function(head){
let current = head
}

In order to find out if there are any duplicates in a sorted list, we have to loop through each node and compare their values.

var deleteDuplicates = function(head){
let current = head
while (head && head.next){
if (head.val == head.next.val) {
head.next = head.next.next
}}}

If the values are equal, then we skip the duplicate and reassign the current value and the current.next.value. If the values are not equal, then we continue to traverse the list to compare the values. Finally we return the sorted linked list.

var deleteDuplicates = function(head){
let current = head
while (head && head.next){
if (head.val == head.next.val) {
head.next = head.next.next
} else {
head = head.next
}
}
return current
}

Conclusion:
So far I found this problem to be more enjoyable to solve so far! Even though this problem uses basic logic, I was humbled by the usage of properties I’ve never used before like .val and .next.I was also equally perplexed and frustrated at trying to translate my pseudocode into working code. Personally, I think we often think too much into what the challenge is asking us. But I walk away humbled knowing I learned something new from this seemingly simple problem!

Below are some helpful resources I found in helping me understand the basics of linked lists and logic behind the problem!

--

--

Melissa Guachun

Software Developer and visual artist based in NYC. Join me on my journey to coding enlightenment or a torrential mental breakdown, whichever comes first.