Problem 203

Abstract / Summary

Remove all nodes from a linked list that have a specific value and return the modified list.

Note

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

Python 0203.py

class Solution:
    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
        if not head:
            return None

        head.next = self.removeElements(head.next, val)
        if head.val == val:
            head = head.next

        return head
10 lines | 294 bytes | submitted September 6, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (3+ million submissions).

Typical patterns to solve this problem:
  • Linked List
  • Recursion
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 defines a method that removes all nodes containing a specified value from a singly-linked list. It follows a recursive strategy: the function processes the list from the head toward the tail, rebuilding the list on the way back while skipping nodes whose val matches the target. The recursion terminates when it reaches the end of the list, ensuring that every node is examined exactly once.

Key Steps

The algorithm can be broken down into three logical sections, each reflected directly in the source code.

Base Case for an Empty List

if not head:
    return None

When the input head reference is None, the function immediately returns None. This condition stops further recursion and represents the situation where the original list is empty or the recursion has advanced past the last node.

Recursive Descent

head.next = self.removeElements(head.next, val)

Before deciding whether to keep the current node, the method recursively processes the remainder of the list (head.next). The result of the recursive call-either a shortened list or None-is assigned back to head.next. This step ensures that the sub-list starting at the original head.next is already cleaned of the target value when the current frame resumes.

Conditional Removal of the Current Node

if head.val == val:
    head = head.next

After the recursive call returns, the current node’s value is compared against the target val. If they are equal, the node is effectively removed by reassigning head to its successor (head.next). Because head.next already points to a list that has been processed, the removal does not disrupt the integrity of the remaining structure.

Return of the Updated Head

return head

The method concludes by returning the possibly updated head. If the original head was removed, the returned reference points to the next valid node; otherwise, it returns the original head, now linked to a cleaned sub-list.

Edge Cases Handled

The recursion naturally accommodates several edge conditions without additional code.

When the list consists of a single node whose value matches val, the base case is reached after the recursive call on head.next (which is None). The conditional removal then sets head to None, and the method returns None, correctly representing an empty list.

If multiple consecutive nodes contain val, each recursive frame will evaluate its own head.val. The conditional removal will skip each matching node, and the linking of the remaining nodes is handled by the assignment head.next = … in the previous frame. This ensures that long runs of unwanted values are eliminated in a single pass.

When the target value appears at the tail of the list, the recursion reaches the tail node, processes it, and the conditional removal discards it. The preceding node’s next pointer, already set to the result of the recursive call, becomes None, correctly terminating the list.

If the target value never appears, the conditional block never executes, and each node simply forwards the cleaned sub-list (which is identical to the original) upward. The final returned head is the original head, preserving the list unchanged.

Performance Optimizations Observed

The implementation leverages the call stack to propagate the cleaned sub-list upward, eliminating the need for an auxiliary data structure or explicit iteration variables. By assigning the result of the recursive call directly to head.next, the method avoids creating new node objects; it reuses the existing nodes, thereby minimizing memory allocation overhead.

Because each node is visited exactly once and the linking operation is performed in constant time, the algorithm maintains a tight execution path. The recursion depth matches the length of the list, which, in environments with optimized tail-call handling, can be executed with minimal stack overhead. Even without tail-call optimization, the straightforward stack usage remains predictable and bounded by the list size.

Overall, the code presents a concise, self-contained solution that efficiently removes unwanted elements while preserving the original node objects and their order.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of toy trains hooked together, one after another. Each train carries a number written on its side. Your job is to go through the whole line and take away any train that has a specific number on it, like the number five.

The computer handles this by looking at the very first train and then asking the rest of the line behind it to do the same task. This happens over and over until reaching the very last caboose. Once the line has finished checking itself, the computer looks at the train it started with. If that train has the forbidden number, it simply hops over it to skip it. This leaves a new, shorter line where all the trains with that number are gone, and everything else is still perfectly connected.

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 | μ = 7.23 | σ = 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 C# Rust Java Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
52 links | 36 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Remove Linked List Elements - Leetcode 203'
NeetCode 8 mins
Remove Linked List Elements - Leetcode 203
YouTube video 'LeetCode 203. Remove Linked List Elements Solution Explained - Java'
Nick White 5 mins
LeetCode 203. Remove Linked List Elements Solution Explained - Java
YouTube video 'Remove Linked List Elements (Recursive, Iterative) | LeetCode 203 | C++, Java, Python'
Knowledge Center 15 mins
Remove Linked List Elements (Recursive, Iterative) | LeetCode 203 | C++, Java, Python
YouTube video 'Remove Linked List Elements | LeetCode 203 | Coding Interview Tutorial'
Terrible Whiteboard 13 mins
Remove Linked List Elements | LeetCode 203 | Coding Interview Tutorial
YouTube video 'Remove Linked List Elements | Leet code 203 | Theory explained + Python code'
Sai Anish Malla 4 mins
Remove Linked List Elements | Leet code 203 | Theory explained + Python code
YouTube video 'Remove Linked List Elements - Google Interview Questions - LeetCode 203 Solution - C++'
nexTRIE 3 mins
Remove Linked List Elements - Google Interview Questions - LeetCode 203 Solution - C++
YouTube video 'LeetCode 203. Remove Linked List Elements'
Engineering Digest 3 mins
LeetCode 203. Remove Linked List Elements
YouTube video 'remove linked list elements | remove linked list elements leetcode | leetcode 203 |'
Naresh Gupta 8 mins
remove linked list elements | remove linked list elements leetcode | leetcode 203 |
YouTube video 'Remove Linked List Elements | LeetCode 203 | Easy'
Code And Coffee 8 mins
Remove Linked List Elements | LeetCode 203 | Easy
YouTube video 'Remove Linked List Elements | Day 20 | [ July LeetCoding Challenge ] [ Leetcode #203] [ 2020 ]'
Algorithms Made Easy 5 mins
Remove Linked List Elements | Day 20 | [ July LeetCoding Challenge ] [ Leetcode #203] [ 2020 ]
YouTube video 'Remove Linked List Elements LeetCode 203 JavaScript O(N) solution. GitHub repo below.'
Team Evan Codes 8 mins
Remove Linked List Elements LeetCode 203 JavaScript O(N) solution. GitHub repo below.
YouTube video '203. Remove Linked List Elements | LEETCODE | IMPORTANT INTERVIEW PROBLEM | LINKED LIST'
code Explainer 10 mins
203. Remove Linked List Elements | LEETCODE | IMPORTANT INTERVIEW PROBLEM | LINKED LIST
YouTube video 'Remove Linked List Elements - LeetCode 203 - Java'
LeetCode University 17 mins
Remove Linked List Elements - LeetCode 203 - Java
YouTube video 'Leetcode 203 Remove Linked List Elements (Java)'
TheAnalyticGuy 4 mins
Leetcode 203 Remove Linked List Elements (Java)
YouTube video '203. Remove Linked List Elements | Java | Leetcode | Linked List | DSA'
Coding with Tamilarasan 12 mins
203. Remove Linked List Elements | Java | Leetcode | Linked List | DSA
YouTube video 'Remove Linked List Elements | Leetcode 203 | Live coding session 🔥🔥🔥🔥'
Coding Decoded 8 mins
Remove Linked List Elements | Leetcode 203 | Live coding session 🔥🔥🔥🔥
YouTube video 'LeetCode 203: Remove Linked List Elements | C# Solution | Dummy Node Pattern |'
Code Scribbler 6 mins
LeetCode 203: Remove Linked List Elements | C# Solution | Dummy Node Pattern |
YouTube video 'Remove Linked List Elements | LeetCode 203 | Coders Camp'
Coders Camp 6 mins
Remove Linked List Elements | LeetCode 203 | Coders Camp
YouTube video 'Leetcode 203 - Remove Linked List Elements (JAVA Solution Explained!)'
LC Bear 6 mins
Leetcode 203 - Remove Linked List Elements (JAVA Solution Explained!)
YouTube video 'Daily Leetcode #591: Nov 12, 2021 - 203. Remove Linked List Elements'
Programming Live with Larry 9 mins
Daily Leetcode #591: Nov 12, 2021 - 203. Remove Linked List Elements
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

25 easy 22 medium 5 hard
53 solutions   September 6, 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