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
Difficulty
and has an acceptance rate of about 52% (2+ million submissions).
Typical patterns to solve this problem:
- Linked List
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 83: Remove Duplicates from Sorted List
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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