Tensorum
LeetCode 237 · Basics

Delete Node in a Linked List

LeetCode 237 · Medium · solution, intuition & step-by-step walkthrough

Copy next's value, then skip next.

MediumLinked List
66 msruntime · beats 5%
52.8 MBmemory · beats 100%
1approach
4accepted runs · last 11 Dec 2024

This is how I solved Delete Node in a Linked List (LeetCode 237), a medium problem from the Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

You only get the node to delete, not its predecessor, so you can't unlink it. Instead, copy the next node's value into it and unlink the next node — the list now looks as if this node was removed.

Approach

  1. 1

    temp = node.next.

  2. 2

    node.val = temp.val.

  3. 3

    node.next = node.next.next.

How I solved it

Copy and skipPythonO(1)
class Solution:
    def deleteNode(self, node):
        temp = node.next
        node.val = temp.val
        node.next = node.next.next
Loading the step-through…

Delete Node in a Linked List — FAQ

What is the intuition behind Delete Node in a Linked List?

You only get the node to delete, not its predecessor, so you can't unlink it. Instead, copy the next node's value into it and unlink the next node — the list now looks as if this node was removed.

How do you solve Delete Node in a Linked List (LeetCode 237)?

1. temp = node.next. 2. node.val = temp.val. 3. node.next = node.next.next.

What is the time and space complexity of Delete Node in a Linked List?

Time: O(1). Space: O(1). (Accepted approach: Copy and skip.)

What are common mistakes in Delete Node in a Linked List?

Works only because the node is never the tail.