Python 0237.py
class Solution:
def deleteNode(self, node):
prev = node
while node.next:
node.val = node.next.val
prev = node
node = node.next
prev.next = None
Difficulty
and has an acceptance rate of about 84% (2+ 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 provided implementation defines a method deleteNode that removes a node from a singly-linked list when only a reference to that node is available. The algorithm works by shifting the values of subsequent nodes forward until the end of the list is reached, then truncates the list by severing the final link. This approach enables deletion without needing access to the list head or a previous pointer.
Core Logic
The method begins by storing the original node reference in a variable named prev. This variable will ultimately point to the node that precedes the last element after the traversal loop.
prev = node
A while loop drives the main transformation. As long as the current node has a successor, the value of the successor is copied into the current node, effectively overwriting the target node’s original value. After the copy, prev is updated to the current node, and the traversal proceeds to the next node.
while node.next:
node.val = node.next.val
prev = node
node = node.next
When the loop exits, node references the final element of the list, and prev references the element that now holds the duplicated value of the former last node. The final step disconnects the last node by setting the next pointer of prev to None.
prev.next = None
The combination of value propagation and pointer adjustment results in the logical removal of the original node from the list.
Edge Cases Handled
The algorithm gracefully handles the situation where the node to be deleted is the only element in the list. In that scenario, the while condition node.next evaluates to false immediately, leaving prev equal to the original node. Setting prev.next = None simply ensures that the solitary node’s next reference is None, which is already the case, leaving the list in a consistent state.
Another implicit edge case is when the node to be deleted is the tail of the list. Because the loop condition requires a successor, the body is never executed for a tail node. Consequently, prev remains pointing to the tail itself, and the final assignment prev.next = None does not alter the list structure. While the method’s contract assumes the node is not the tail (as deletion would be impossible without a predecessor), the code does not raise an error and leaves the list unchanged, thereby avoiding a crash.
Performance Optimizations
The implementation avoids allocating additional data structures or creating new node objects. By reusing the existing nodes and merely copying values, it minimizes memory overhead. The traversal proceeds in a single pass from the target node to the end of the list, ensuring that each node is visited at most once. Updating the prev reference inside the loop eliminates the need for a secondary pass to locate the predecessor of the final node, thereby reducing the total number of pointer dereferences. This in-place modification strategy yields an efficient solution within the constraints of the problem.
ELI5 - Simplified Explanation
Imagine a long line of toy trains all hooked together. Each train has a little sticker on it with a number.
This code is like a helper who wants to remove one train from the middle of the line without leaving a gap. To do this, the helper starts at the train that needs to be taken away. Instead of pulling it out, the helper looks at the next train in line and copies the number from that train onto the current train's sticker. Then, the helper moves to that next train and does the same thing again and again, copying numbers all the way down the line.
Once all the numbers have been shifted forward like a game of musical chairs, the helper reaches the very last train. Because all the numbers are now in the right spot, the helper simply unhooks the last train and lets it go, leaving the line perfectly connected but one train shorter.
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# | Java | C | JS | Go | TS | ||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| qiyuangong | Python | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| DimitrisJim | C | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| FelixFan1122 | C# | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| gaosq0604 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| Krazune | C++ | |||||||||
| lennylxx | C | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| muhammadfarhankt | Go | |||||||||
| qiyuangong | Python | |||||||||
| shreymehul | C# | |||||||||
| sonugiri1043 | C++ | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| vthwang | Java | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 203: Remove Linked List Elements
- problem 2487: Remove Nodes From Linked List
- problem 3217: Delete Nodes From Linked List Present in Array
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 560: Subarray Sum Equals K
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
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