Problem 82

Abstract / Summary

Remove all nodes with duplicate values so each number appears only once in the sorted list.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0082.py

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def unique(node):
            if not node or not node.next:
                return True
            else:
                return node.val != node.next.val

        def skip(node):
            value = node.val
            while node and node.val == value:
                node = node.next
            return node


        while not unique(head):
            head = skip(head)

        lookahead = head
        while lookahead and lookahead.next:
            while not unique(lookahead.next):
                lookahead.next = skip(lookahead.next)
            lookahead = lookahead.next

        return head
25 lines | 735 bytes | submitted August 31, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (2+ million submissions).

Typical patterns to solve this problem:
  • Linked List
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of removing all nodes that have duplicate values from a singly-linked list, leaving only distinct elements. It does so by defining two small helper functions-unique and skip-and then applying them in two phases: first to discard any duplicate block that appears at the head of the list, and second to walk through the remainder of the list, reconnecting the next pointers whenever a duplicate block is encountered. The algorithm works in-place, reusing the existing nodes without allocating additional list structures.

Unique Check Helper

The unique function determines whether a given node is the sole occurrence of its value with respect to its immediate successor. If the node is None or has no next node, it is trivially unique. Otherwise the function returns the result of a simple inequality comparison between the current node’s value and the next node’s value.

def unique(node):
    if not node or not node.next:
        return True
    else:
        return node.val != node.next.val

This helper abstracts the “is this node the start of a duplicate run?” test, allowing the main loops to remain concise.

Skip Duplicates Helper

The skip function advances a pointer past an entire block of nodes that share the same value. It captures the value of the starting node, then iterates while the current node exists and its value matches the captured one, moving to the next node each iteration. The function finally returns the first node whose value differs, or None if the end of the list is reached.

def skip(node):
    value = node.val
    while node and node.val == value:
        node = node.next
    return node

By collapsing a whole duplicate segment in a single pass, skip eliminates the need for repeated pointer adjustments inside the main traversal.

Removing Leading Duplicates

Before processing the interior of the list, the algorithm ensures that the head points to a unique value. It repeatedly checks the head with unique; if the head is part of a duplicate block, skip moves the head forward to the first distinct node. This loop terminates as soon as the head is either None or points to a unique element.

while not unique(head):
    head = skip(head)

This step gracefully handles cases where the entire list consists of duplicates, resulting in a None return, as well as scenarios where the first few nodes are duplicated but later unique nodes exist.

Traversing the List

After establishing a clean head, the algorithm uses a pointer named lookahead to walk through the list. For each node, it examines the next node: if next begins a duplicate block (unique returns False), the next pointer is redirected to the node returned by skip, effectively excising the duplicate segment. The inner loop repeats until the next node is unique, then the outer loop advances lookahead to its next.

lookahead = head
while lookahead and lookahead.next:
    while not unique(lookahead.next):
        lookahead.next = skip(lookahead.next)
    lookahead = lookahead.next

This structure guarantees that every duplicate run is removed, and that the traversal proceeds only over nodes that have survived the deduplication process.

Edge Cases Handled

The code correctly processes an empty input list because the initial unique call receives None and returns True, causing the head-cleaning loop to be bypassed and the function to return None.

When the list contains a single node, unique also returns True, leaving the node untouched.

If the list is composed entirely of identical values, the head-cleaning loop repeatedly invokes skip until head becomes None, and the function returns None.

When duplicate blocks appear at the tail of the list, the inner loop redirects the next pointer of the preceding unique node to the node after the duplicate block, which may be None, thereby truncating the list correctly.

Mixed patterns of unique and duplicate nodes are handled seamlessly because the algorithm always checks the immediate successor before deciding to skip.

Performance Optimizations

The design avoids auxiliary data structures such as hash tables or additional linked-list nodes, thereby keeping memory usage minimal.

Both helper functions operate with simple pointer moves and constant-time comparisons, ensuring that each node is visited at most twice: once during the initial head cleanup (if applicable) and once during the main traversal.

The inner while not unique(lookahead.next) loop collapses an entire duplicate segment in a single call to skip, preventing repeated reassignment of lookahead.next for each node inside the duplicate block. This reduces the number of pointer updates and conditional checks, especially beneficial when long runs of duplicates are present.

By reusing the original list nodes and only adjusting next references, the algorithm eliminates the overhead of node allocation and garbage collection that would arise from constructing a new list.

Overall, the implementation achieves an efficient in-place removal of all duplicate values while maintaining a clear and modular structure.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long parade of toy trains connected in a line. Each train has a special number painted on its side. Sometimes, two or more trains right next to each other have the same number, which is a bit messy. The goal is to remove all the trains that have duplicate numbers so that only the ones with unique numbers stay in the parade.

The code starts by looking at the very first train. If the first train and the one behind it have the same number, they are both part of a group that needs to go away. It keeps skipping over the trains until it finds one that is different from the others.

Once the front of the line is handled, the code moves down the row one train at a time. It checks the train that is coming up next. If the next train and the one after that have the same number, it means there is a cluster of duplicate trains to remove. It skips over that whole group of identical trains by pointing to the next train that is different. It keeps doing this for every train in the line until it reaches the very end. By the time it finishes, all the trains left standing in the parade have numbers that are completely different from their neighbors.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.19 | σ = 1.42

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel Python
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel Python
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
54 links | 37 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Remove Duplicates from Sorted List II | Live Coding with Explanation | Leetcode - 82'
Algorithms Made Easy 6 mins
Remove Duplicates from Sorted List II | Live Coding with Explanation | Leetcode - 82
YouTube video 'Remove Duplicates from Sorted List 2 (LeetCode 82) | Full Solution with animations'
Nikhil Lohia 13 mins
Remove Duplicates from Sorted List 2 (LeetCode 82) | Full Solution with animations
YouTube video 'Remove Duplicates from Sorted List II | Leetcode 82| Linked List | Day-9'
Ayushi Sharma 18 mins
Remove Duplicates from Sorted List II | Leetcode 82| Linked List | Day-9
YouTube video 'Remove Duplicates from Sorted List II (RECURSIVE) | LeetCode 82 | C++, Java, Python'
Knowledge Center 11 mins
Remove Duplicates from Sorted List II (RECURSIVE) | LeetCode 82 | C++, Java, Python
YouTube video 'LeetCode 82. Remove Duplicates from Sorted List II'
Engineering Digest 7 mins
LeetCode 82. Remove Duplicates from Sorted List II
YouTube video '[Java] Leetcode 82. Remove Duplicates from Sorted List II [Two Pointers #10]'
Eric Programming 7 mins
[Java] Leetcode 82. Remove Duplicates from Sorted List II [Two Pointers #10]
YouTube video 'LeetCode 82. Remove Duplicates from Sorted List II'
Happy Coding 11 mins
LeetCode 82. Remove Duplicates from Sorted List II
YouTube video 'Leetcode 82 Remove Duplicates from Sorted List II (Java)'
TheAnalyticGuy 9 mins
Leetcode 82 Remove Duplicates from Sorted List II (Java)
YouTube video 'LeetCode 82 | Remove Duplicates from Sorted Linked List II | Solution Explained (Java)'
Xavier Elon 5 mins
LeetCode 82 | Remove Duplicates from Sorted Linked List II | Solution Explained (Java)
YouTube video 'Remove Duplicates from Sorted List II | remove duplicates from sorted list ii | LeetCode 82 | list'
Naresh Gupta 12 mins
Remove Duplicates from Sorted List II | remove duplicates from sorted list ii | LeetCode 82 | list
YouTube video 'Remove Duplicates from Sorted List II | Leetcode 82 | Live coding session'
Coding Decoded 11 mins
Remove Duplicates from Sorted List II | Leetcode 82 | Live coding session
YouTube video '82. Remove Duplicates from Sorted List II | Leetcode | Python'
Abdullah Arshed 7 mins
82. Remove Duplicates from Sorted List II | Leetcode | Python
YouTube video 'Remove Duplicates from Sorted List II | Leetcode 82  | Easy  Linked List  | Live coding session 🔥🔥'
Coding Decoded 3 mins
Remove Duplicates from Sorted List II | Leetcode 82 | Easy Linked List | Live coding session 🔥🔥
YouTube video 'Can You Remove Duplicates? (LeetCode 82: Remove Duplicates from Sorted List II)'
Code With Zi 11 mins
Can You Remove Duplicates? (LeetCode 82: Remove Duplicates from Sorted List II)
YouTube video '82. Remove Duplicates from Sorted List II | Java | Leetcode | Linked List | DSA'
Coding with Tamilarasan 13 mins
82. Remove Duplicates from Sorted List II | Java | Leetcode | Linked List | DSA
YouTube video 'Daily Leetcode #708: Mar 09, 2022 - 82. Remove Duplicates from Sorted List II'
Programming Live with Larry 9 mins
Daily Leetcode #708: Mar 09, 2022 - 82. Remove Duplicates from Sorted List II
YouTube video 'Daily Leetcode #280: Jan 05, 2021 - 82. Remove Duplicates from Sorted List II'
Programming Live with Larry 13 mins
Daily Leetcode #280: Jan 05, 2021 - 82. Remove Duplicates from Sorted List II
YouTube video '82. Remove Duplicates from Sorted List II | LEETCODE MEDIUM | LINKED LIST'
code Explainer 8 mins
82. Remove Duplicates from Sorted List II | LEETCODE MEDIUM | LINKED LIST
YouTube video '82. Remove Duplicates from Sorted List II || Leetcode Medium || Cpp'
Komal Pal 11 mins
82. Remove Duplicates from Sorted List II || Leetcode Medium || Cpp
YouTube video 'Day 222: LeetCode Problem 82. Remove Duplicates from Sorted List II - Swift'
iOSxBank 14 mins
Day 222: LeetCode Problem 82. Remove Duplicates from Sorted List II - Swift
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality