C++ 0083.cpp
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto current = head;
while (current)
{
auto next = current->next;
while (next && next->val == current->val)
next = next->next;
current->next = next;
current = next;
}
return head;
}
};
Difficulty
and has an acceptance rate of about 57% (4+ million submissions).
Typical patterns to solve this problem:
- Linked List
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 function removes consecutive duplicate values from a singly-linked list while preserving the original order of distinct elements. It works directly on the input list, adjusting the next pointers to bypass nodes that share the same value as their predecessor. The algorithm proceeds from the head toward the tail, ensuring that each node is visited at most once.
Initialization of the traversal pointer
The first step captures the head of the list in a local variable that will be used to walk through the structure.
auto current = head;
By storing the head in current, the code isolates the traversal logic from the external reference, allowing the function to modify links without losing access to the list’s start.
Inner loop that skips over equal-valued nodes
For each node pointed to by current, the algorithm looks ahead to find the first node whose value differs. This is achieved with a nested loop that advances a secondary pointer until the condition fails.
auto next = current->next;
while (next && next->val == current->val)
next = next->next;
The guard next && protects against dereferencing a null pointer when the end of the list is reached. The loop stops precisely when a node with a new value is encountered or when the list terminates.
Relinking the current node to the next distinct node
Once the first distinct successor has been identified, the next field of the current node is updated to point to it. This effectively removes all intermediate duplicates from the chain.
current->next = next;
current = next;
Assigning current = next moves the outer traversal forward, ready to repeat the process for the next segment of distinct values. If next is nullptr, the outer loop terminates because the condition while (current) becomes false.
Edge-case handling embedded in the logic
The implementation gracefully deals with several boundary situations without extra code:
- An empty list (
headisnullptr) results incurrentbeingnullptr; the outer loop never executes and the originalnullptris returned. - A list containing a single node bypasses the inner loop because
current->nextisnullptr; the node is returned unchanged. - A list where every element is identical causes the inner loop to march to the end, setting
current->nexttonullptrand terminating the traversal after the first node. - A list with no consecutive duplicates never enters the inner loop; each node’s
nextpointer is reassigned to its original successor, leaving the list intact.
Performance-focused characteristics
The algorithm operates in a single pass, touching each node only while searching for the next distinct value. By reusing the existing node objects and merely rewiring pointers, it avoids any dynamic memory allocation or copying of node contents. The use of local pointer variables (current, next) keeps the working set small and cache-friendly, which contributes to fast execution even on long lists. Because the function returns the original head pointer, no additional data structures are created, and the memory footprint remains constant throughout the execution.
ELI5 - Simplified Explanation
Imagine a long train made of several little cars hooked together in a line. Some of the cars are exactly the same, like having two blue cars right next to each other. This code is like a helper walking along the train to tidy it up.
The helper starts at the very front of the train and looks at the car they are standing on. Then, they peek at all the cars coming right after it to see if any of them match the one they are holding onto. If the helper finds cars that look just like the current one, they skip over them and throw them away by connecting the current car to the next different one they find. Once the helper is sure all the duplicates are gone, they jump to that next different car and start the whole process over again. This keeps happening until the helper reaches the very end of the train, leaving only one of each kind of car behind in the line.
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 | Rust | Java | JS | C# | Go | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | AdelDaniel | Dart | ||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| AdelDaniel | Dart | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| pruthvikp | Python | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 82: Remove Duplicates from Sorted List II
- problem 1836: Remove Duplicates From an Unsorted Linked List
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
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