Remove Linked List Elements - Problem
You're given the head of a linked list and an integer val. Your task is to remove all nodes from the linked list that contain the value val, and return the new head of the modified list.

This is a classic linked list manipulation problem that tests your understanding of pointer management and edge case handling. You'll need to consider scenarios like removing the head node, removing consecutive nodes, or even removing all nodes from the list.

Key Challenge: The tricky part is handling cases where the head node itself needs to be removed, which requires careful pointer manipulation to avoid losing the reference to the new list.

Input & Output

example_1.py โ€” Remove Middle Elements
$ Input: head = [1,2,6,3,4,5,6], val = 6
โ€บ Output: [1,2,3,4,5]
๐Ÿ’ก Note: The nodes with value 6 are at positions 2 and 6 (0-indexed). After removing these nodes, the remaining list becomes [1,2,3,4,5].
example_2.py โ€” Empty List
$ Input: head = [], val = 1
โ€บ Output: []
๐Ÿ’ก Note: The input list is already empty, so removing any value results in an empty list.
example_3.py โ€” Remove All Elements
$ Input: head = [7,7,7,7], val = 7
โ€บ Output: []
๐Ÿ’ก Note: All nodes in the list have the value 7, so removing all occurrences of 7 results in an empty list.

Constraints

  • The number of nodes in the list is in the range [0, 104]
  • -50 โ‰ค Node.val โ‰ค 50
  • 0 โ‰ค val โ‰ค 50

Visualization

Tap to expand
๐Ÿš‚ Train Car Removal Analogy๐Ÿš‚DUMMYEngine1Keep2Keep6Remove3Keep4Keep5Keep6RemoveGreen connections show relinking to skip removed carsAfter Removal Process:12345
Understanding the Visualization
1
Station Setup
Place a dummy engine at the front to simplify operations
2
Inspection Walk
Walk along the train checking each car's cargo
3
Car Removal
When finding target cargo, disconnect that car and relink neighbors
4
Final Assembly
Return the train starting from the first real car
Key Takeaway
๐ŸŽฏ Key Insight: Using a dummy head eliminates the complexity of special case handling, making the removal process uniform for all nodes including the original head.
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22
82.2K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen