Problem 237

Abstract / Summary

Given a node in a singly linked list, remove it from the list assuming access to only that node.

Note

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

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
9 lines | 218 bytes | submitted September 4, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (2+ 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 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.

written by openai gpt

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.

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 = 6 | μ = 5.50 | σ = 1.74

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# 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++
54 links | 37 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Delete Node in a Linked List | Super Easy | Apple | Microsoft | Leetcode 237'
codestorywithMIK 13 mins
Delete Node in a Linked List | Super Easy | Apple | Microsoft | Leetcode 237
YouTube video 'LeetCode 237. Delete Node in a Linked List Solution Explained - Java'
Nick White 3 mins
LeetCode 237. Delete Node in a Linked List Solution Explained - Java
YouTube video 'Delete Node in a Linked List | LeetCode 237 | C++, Java, Python'
Knowledge Center 7 mins
Delete Node in a Linked List | LeetCode 237 | C++, Java, Python
YouTube video '237. Delete Node in a Linked List || Java || Leetcode || Hindi'
Coding Sphere 4 mins
237. Delete Node in a Linked List || Java || Leetcode || Hindi
YouTube video 'Delete Node in a Linked List | Day 2 | [June LeetCoding Challenge] [Leetcode #237] [2020]'
Algorithms Made Easy 3 mins
Delete Node in a Linked List | Day 2 | [June LeetCoding Challenge] [Leetcode #237] [2020]
YouTube video 'Delete Node in a Linked List | Leetcode 237'
Ayushi Sharma 7 mins
Delete Node in a Linked List | Leetcode 237
YouTube video 'LEETCODE 237 (JAVASCRIPT) | DELETE A NODE IN A LINKED LIST'
Andy Gala 6 mins
LEETCODE 237 (JAVASCRIPT) | DELETE A NODE IN A LINKED LIST
YouTube video '237. Delete Node in a Linked List | Singly Linked List | Easy |'
Aryan Mittal 8 mins
237. Delete Node in a Linked List | Singly Linked List | Easy |
YouTube video 'Delete a Node in Linked List: HackerRank Data Structures Solutions in C/C++'
nexTRIE 5 mins
Delete a Node in Linked List: HackerRank Data Structures Solutions in C/C++
YouTube video 'LeetCode 237: Delete Node in a Linked List - Interview Prep Ep 57'
Fisher Coder 11 mins
LeetCode 237: Delete Node in a Linked List - Interview Prep Ep 57
YouTube video 'Delete Node in a Linked List - LeetCode 237 - Python  #leetcode #linkedlist'
Deepti Talesra 7 mins
Delete Node in a Linked List - LeetCode 237 - Python #leetcode #linkedlist
YouTube video 'Delete Node in a Linked List  (LeetCode 237) (How to Think out of the Box)'
CodeWithARB 11 mins
Delete Node in a Linked List (LeetCode 237) (How to Think out of the Box)
YouTube video 'Leetcode 237: Delete Node in a Linked List | Python in Telugu | 2 Line Solution | srkcodes'
Srk Codes 5 mins
Leetcode 237: Delete Node in a Linked List | Python in Telugu | 2 Line Solution | srkcodes
YouTube video 'Daily Leetcode #1496: May 05, 2024 - 237. Delete Node in a Linked List'
Programming Live with Larry 8 mins
Daily Leetcode #1496: May 05, 2024 - 237. Delete Node in a Linked List
YouTube video '237. Delete Node in a Linked List | LeetCode Daily Challenge | JavaScript | Understandable | TC O(1)'
LeetCodeWithMonu 7 mins
237. Delete Node in a Linked List | LeetCode Daily Challenge | JavaScript | Understandable | TC O(1)
YouTube video 'Leetcode 237 Delete Node in a Linked List |  Coding Decoded SDE Sheet'
Coding Decoded 4 mins
Leetcode 237 Delete Node in a Linked List | Coding Decoded SDE Sheet
YouTube video 'Delete Node in a Linked List | Leetcode June Day 02 | Problem 237 | Easy'
Naresh Gupta 5 mins
Delete Node in a Linked List | Leetcode June Day 02 | Problem 237 | Easy
YouTube video 'Delete Node in a Linked List without head node| Java| Leetcode 237 | Linked List'
Coding Env 7 mins
Delete Node in a Linked List without head node| Java| Leetcode 237 | Linked List
YouTube video 'Daily Leetcode #926: Oct 13, 2022 - 237. Delete Node in a Linked List'
Programming Live with Larry 7 mins
Daily Leetcode #926: Oct 13, 2022 - 237. Delete Node in a Linked List
YouTube video 'Delete a Node in Single Linked List || C++ || GFG Daily Problem'
CodeFreaks 5 mins
Delete a Node in Single Linked List || C++ || GFG Daily Problem
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

4 easy 20 medium
25 solutions   September 4, 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