↓Skip to main content
  1. LeetCode/

LeetCode 237: Delete Node in a Linked List

·1 min· ·
LeetCode Medium Linked-List
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-08-22

  • Submissions: Accepted (first try)

Approach
#

Only the node to delete is given, not its predecessor, so nothing can skip over it. Instead copy the next node’s value into this one and delete the next node (Linked List, Others). The node is guaranteed not to be the tail, so the next node exists.

My Solution
#

class Solution:
    def deleteNode(self, node):
        node.val = node.next.val
        node.next = node.next.next

Complexity
#

Time O(1), space O(1).

Mistakes to Avoid
#

  • This trick only works when the node is not the tail.

Interview Explanation
#

Without the predecessor the node cannot truly remove itself, so I copy the next node’s value and skip the next node, which has the same effect. Time O(1).

Related

LeetCode 2: Add Two Numbers
·2 mins
LeetCode Medium Linked-List Math Recursion
LeetCode 2 note: digits are stored in reverse, so add from the head digit by digit with a carry, looping until both lists end and no carry remains
LeetCode 234: Palindrome Linked List
·2 mins
LeetCode Easy Linked-List Two-Pointers Stack Recursion
LeetCode 234 note: find the middle with fast and slow pointers, reverse the second half, and compare from both ends with O(1) extra space
LeetCode 235: Lowest Common Ancestor of a Binary Search Tree
·2 mins
LeetCode Medium Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 235 note: go left when both p and q are smaller, right when both are larger; otherwise (split, or one is the node itself) this node is the LCA
LeetCode 203: Remove Linked List Elements
·2 mins
LeetCode Easy Linked-List Recursion
LeetCode 203 note: the head may be deleted too, so a dummy head turns every deletion into deleting cur.next; do not advance after deleting
LeetCode 206: Reverse Linked List
·1 min
LeetCode Easy Linked-List Recursion
LeetCode 206 note: three pointers prev / cur / nxt; save the next node, then point cur.next back at prev
LeetCode 141: Linked List Cycle
·2 mins
LeetCode Easy Hash-Table Linked-List Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 141 note: Floyd’s cycle detection, fast two steps and slow one; with a cycle they must meet, each advancing from its own position