Remove Linked List Elements (LeetCode 203): Solution and Explanation

Easy
Linked List
Recursion

Given the head of a singly linked list and a value val, remove every node whose value equals val and return the head of the resulting list. The head itself may need removing, possibly several times in a row.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Removing a node from a singly linked list means changing the next pointer of the node before it so that it skips over the node you want gone. That immediately tells you the traversal must keep track of the previous node, because once you are standing on a node you cannot reach backward.

The awkward part is the head. If the first node matches, there is no previous node to rewire, so a naive solution ends up with a special loop at the start that keeps advancing head while it matches, followed by the general loop for the rest. That works but duplicates logic and is easy to get wrong when the list is something like 7, 7, 7, 7.

A dummy node removes the special case entirely. Create a placeholder node whose next is the real head, and start prev at the dummy. Now every real node, including the first, has a predecessor. Walk curr through the list. When curr matches, splice it out with prev.next = curr.next and leave prev where it is, since the next node could also match. When it does not match, move prev forward to curr. At the end, dummy.next is the new head, which correctly handles the case where every node was removed.

Approach: Dummy head with previous and current pointers

  1. Create dummy = ListNode(0, head) so that the real head has a predecessor.
  2. Set prev = dummy and curr = head.
  3. While curr is not None, check whether curr.val == val.
  4. If it matches, set prev.next = curr.next to unlink curr, and keep prev in place.
  5. If it does not match, advance prev to curr.
  6. In both cases advance curr = curr.next, and when the loop ends return dummy.next.

Step-by-step example

head = [6, 1, 6, 6, 2], val = 6
  1. The dummy points at the first 6. prev is the dummy and curr is that 6. It matches, so dummy.next now points at 1, and prev stays on the dummy.
  2. curr moves to 1, which does not match, so prev advances to the 1 node.
  3. curr moves to the second 6, which matches, so 1.next is set to the third 6. prev stays on 1.
  4. curr moves to the third 6, which also matches, so 1.next is set to 2.
  5. curr moves to 2, which does not match, so prev advances to 2. curr becomes None and the loop ends.
  6. The function returns dummy.next, giving the list [1, 2].

Code: Python, Java, C++

1class Solution:
2    def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
3        dummy = ListNode(0, head)
4        prev, curr = dummy, head
5        while curr:
6            if curr.val == val:
7                prev.next = curr.next
8            else:
9                prev = curr
10            curr = curr.next
11        return dummy.next

Time and space complexity

Time

O(n)

Every node is visited exactly once, and each visit does a constant amount of pointer work.

Space

O(1)

Only the dummy node and two pointers are allocated, no matter how long the list is.

Other approaches

Recursion (time O(n), space O(n))

Recursively clean the rest of the list with head.next = removeElements(head.next, val), then return head.next if the head matches or head otherwise. It is very compact, but each node adds a stack frame, so a list of 10,000 nodes can hit recursion limits in some languages.

Advance the head first, then loop (time O(n), space O(1))

Skip leading matches by moving head forward while head.val == val, then run the same predecessor loop starting from the new head. It avoids allocating a dummy node but needs two loops and careful null checks.

Common mistakes

  • Advancing prev after removing a node. If the next node also matches, prev would then point at a removed node and the second removal would not stick.
  • Returning head instead of dummy.next. When the original head is removed, head still points at the deleted node.
  • Forgetting the all-match case, such as [7, 7, 7] with val = 7. The answer must be an empty list, which the dummy approach returns naturally.
  • In languages with manual memory management, unlinking a node without freeing it, which leaks memory in C++ if the nodes were heap allocated by you.

Frequently asked questions

Why use a dummy node in linked list problems?

A dummy node gives the real head a predecessor, so inserting or deleting at the front uses the same code as anywhere else. It removes special cases and makes the final head simply dummy.next.

Is the recursive solution O(1) space?

No. Each recursive call stays on the call stack until the end of the list is reached, so space is O(n). The iterative dummy-node solution is the constant-space version.

Why does prev not move when a node is removed?

After removing curr, the node now following prev has not been checked yet. Keeping prev in place ensures that if that node also matches, it can be unlinked from the same predecessor.