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
Difficulty
and has an acceptance rate of about 55% (3+ million submissions).
Typical patterns to solve this problem:
- Linked List
- Recursion
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 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.
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.
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 | 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++ |
Videos
Similar Problems
- problem 27: Remove Element
- problem 237: Delete Node in a Linked List
- problem 2095: Delete the Middle Node of a Linked List
- problem 3217: Delete Nodes From Linked List Present in Array
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 607: Sales Person
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 192: Word Frequency
- problem 194: Transpose File
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 585: Investments in 2016
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 626: Exchange Seats
- problem 725: Split Linked List in Parts
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
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