Problem 83

Abstract / Summary

Given a sorted linked list remove duplicate nodes so each value appears only once

Note

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

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;
    }
};
18 lines | 388 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (4+ million submissions).

Typical patterns to solve this problem:
  • Linked List
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 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 (head is nullptr) results in current being nullptr; the outer loop never executes and the original nullptr is returned.
  • A list containing a single node bypasses the inner loop because current->next is nullptr; the node is returned unchanged.
  • A list where every element is identical causes the inner loop to march to the end, setting current->next to nullptr and terminating the traversal after the first node.
  • A list with no consecutive duplicates never enters the inner loop; each node’s next pointer 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8.5 | μ = 8.23 | σ = 1.62

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 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++
58 links | 42 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Remove Duplicates from Sorted List - Leetcode 83 - Python'
NeetCode 11 mins
Remove Duplicates from Sorted List - Leetcode 83 - Python
YouTube video 'LeetCode 83. Remove Duplicates from Sorted List Solution Explained - Java'
Nick White 5 mins
LeetCode 83. Remove Duplicates from Sorted List Solution Explained - Java
YouTube video 'Remove duplicates from a sorted Linked List | Solution'
Pepcoding 7 mins
Remove duplicates from a sorted Linked List | Solution
YouTube video 'Remove Duplicates from Sorted List (LeetCode 83) | Full Solution with animations & Easy Explanation'
Nikhil Lohia 14 mins
Remove Duplicates from Sorted List (LeetCode 83) | Full Solution with animations & Easy Explanation
YouTube video 'Remove Duplicates from Sorted List - Leetcode 83 - Linked Lists (Python)'
Greg Hogg 6 mins
Remove Duplicates from Sorted List - Leetcode 83 - Linked Lists (Python)
YouTube video 'Leetcode | 83. Remove Duplicates from Sorted List | Easy | Java Solution'
Developer Docs 6 mins
Leetcode | 83. Remove Duplicates from Sorted List | Easy | Java Solution
YouTube video 'HackerRank - Remove Duplicates from a Sorted Linked List | Full solution | Study Algorithms'
Nikhil Lohia 16 mins
HackerRank - Remove Duplicates from a Sorted Linked List | Full solution | Study Algorithms
YouTube video '83. Remove Duplicates from Sorted List || Java || Leetcode || Hindi'
Coding Sphere 7 mins
83. Remove Duplicates from Sorted List || Java || Leetcode || Hindi
YouTube video 'LeetCode 83 | Remove Duplicates from Sorted List'
Engineering Digest 4 mins
LeetCode 83 | Remove Duplicates from Sorted List
YouTube video 'Leetcode 83: Remove Duplicates from Sorted List | Python DSA Telugu | Iterative & Recursive'
Srk Codes 10 mins
Leetcode 83: Remove Duplicates from Sorted List | Python DSA Telugu | Iterative & Recursive
YouTube video 'LeetCode 83 | Remove Duplicates from Sorted Linked List (Java + Whiteboard)'
Xavier Elon 5 mins
LeetCode 83 | Remove Duplicates from Sorted Linked List (Java + Whiteboard)
YouTube video 'Can You Remove These Duplicates? (LeetCode 83: Remove Duplicates from Sorted List)'
Code With Zi 5 mins
Can You Remove These Duplicates? (LeetCode 83: Remove Duplicates from Sorted List)
YouTube video 'Leetcode 83 Remove Duplicates from Sorted List (Java)'
TheAnalyticGuy 7 mins
Leetcode 83 Remove Duplicates from Sorted List (Java)
YouTube video 'LeetCode 83: Remove Duplicates from Sorted List | C# Solution | In-place Removal |'
Code Scribbler 7 mins
LeetCode 83: Remove Duplicates from Sorted List | C# Solution | In-place Removal |
YouTube video '83. Remove Duplicates from Sorted List (Leetcode Easy)'
Programming Live with Larry 5 mins
83. Remove Duplicates from Sorted List (Leetcode Easy)
YouTube video 'Remove Duplicates from Sorted List | Leetcode 83 | O(N) Time Complexity #dsa'
Learn With Chirag 4 mins
Remove Duplicates from Sorted List | Leetcode 83 | O(N) Time Complexity #dsa
YouTube video '83. Remove Duplicates from Sorted List - LeetCode 101 - JavaScript Tutorial'
Software Interviews Prep 5 mins
83. Remove Duplicates from Sorted List - LeetCode 101 - JavaScript Tutorial
YouTube video 'Leetcode | Easy | 83. Remove Duplicates from Sorted List | Time complexity: O(n) | Javascript'
Software Interviews Prep 5 mins
Leetcode | Easy | 83. Remove Duplicates from Sorted List | Time complexity: O(n) | Javascript
YouTube video 'Remove Duplicates from Sorted List 1 - Leetcode 83 - Java'
Code With K5KC 8 mins
Remove Duplicates from Sorted List 1 - Leetcode 83 - Java
YouTube video '83. Remove Duplicates from Sorted List | Leetcode | Python'
Abdullah Arshed 4 mins
83. Remove Duplicates from Sorted List | Leetcode | Python
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 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