LeetCode #203 Easy

Remove Linked List Elements

Remove Linked List Elements is LeetCode 203 (Easy). You get the head of a linked list and an integer val. Remove every node whose value equals val and return the new head.

  • The list is not sorted, so matching nodes can be anywhere, including the head and several in a row.
  • The list can be empty, and every node can match, which leaves an empty list.
Constraints
  • The number of nodes in the list is in the range [0, 10⁴].
  • 1 <= Node.val <= 50
  • 0 <= val <= 50
linked-listtwo-pointers
Open on LeetCode ↗
02

Intuition

A singly linked node cannot unlink itself, because the link that has to change belongs to the node before it. So the walk stands on a node and judges the one after it.

  • Judge the next node: if prev.next matches, point prev past it; otherwise move prev onto it.
  • Placeholder in front: the head has no node before it. A dummy node supplies one, so a matching head is removed by exactly the same line as any other node.
How to spot this pattern

Deleting nodes by a test on their value, with the head possibly deleted, is the signal for a dummy node plus a pointer that always looks one node ahead.

03

Approach

Try it first

Before reading on, decide which node you stand on when you delete a node, and what you stand on when the head itself must go. Then trace [7, 7, 7] with val = 7. Aim for O(n) time and O(1) extra space.

1

Add a node in front of the head

Create dummy whose next is head, and set prev = dummy. Now every real node, the head included, has a node before it whose link can be changed.

2

Look at the node after prev

Loop while prev.next exists. The candidate for deletion is always prev.next, never prev, because prev is a node that has already been accepted.

3

Unlink a match, or accept a keeper

If prev.next.val == val, set prev.next = prev.next.next and leave prev where it is, since the node that slid into place is still unjudged. Otherwise move prev forward onto the node it just accepted.

4

Return what follows the placeholder

Return dummy.next. If the old head was deleted this is a later node, and if every node matched it is null, so the placeholder never leaks into the answer.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
▶3 dummy = ListNode(0, head)
▶4 prev = dummy
▶5 while prev.next:
▶6 if prev.next.val == val:
▶7 prev.next = prev.next.next
▶8 else:
▶9 prev = prev.next
▶10 return dummy.next
liststart1263456prevremovedprev starts on the placeholder; remove 6s
val6
prevstart
The placeholder gives the head a node in front of it, so the head can be removed by changing the placeholder's link, like any other node.
liststart1263456prevremoved1 is not 6 → keep it, prev moves on
prev1
1 stays in the list, so prev moves onto it. From there prev can unlink whatever comes next, if that one matches.
liststart1263456prevremoved2 is not 6 → keep it, prev moves on
prev2
2 stays in the list, so prev moves onto it. From there prev can unlink whatever comes next, if that one matches.
liststart123456prevremoved66 equals 6 → unlink it, prev stays
prev2
next3
prev's link now skips the 6. prev stays put because the 3 that slid into place has not been judged yet.
liststart123456prevremoved63 is not 6 → keep it, prev moves on
prev3
3 stays in the list, so prev moves onto it. From there prev can unlink whatever comes next, if that one matches.
liststart123456prevremoved64 is not 6 → keep it, prev moves on
prev4
4 stays in the list, so prev moves onto it. From there prev can unlink whatever comes next, if that one matches.
liststart123456prevremoved65 is not 6 → keep it, prev moves on
prev5
5 stays in the list, so prev moves onto it. From there prev can unlink whatever comes next, if that one matches.
liststart12345prevremoved666 equals 6 → unlink it, prev stays
prev5
nextnone
prev's link now skips the 6. prev stays put because nothing is left after it.
liststart12345removed66nothing after prev → return 1 → 2 → 3 → 4 → 5
return1
Every node was judged once. The answer starts at the placeholder's next node, which is the first node that did not match.
05

Common pitfalls

Stepping prev forward after a removal

✗ Wrong
if prev.next.val == val:
    prev.next = prev.next.next
prev = prev.next
✓ Right
if prev.next.val == val:
    prev.next = prev.next.next
else:
    prev = prev.next

With [1, 6, 6, 2] and val = 6, removing the first 6 brings the second 6 next to 1, and the unconditional step jumps onto it. It is never judged, so the result is [1, 6, 2].

Returning head instead of dummy.next

✗ Wrong
return head
✓ Right
return dummy.next

For [7, 7] with val = 7, head is still the first 7: it was unlinked from the dummy, not changed itself. Its own link to the second 7 never changed, so returning it hands back [7, 7] instead of an empty list.

06

Edge cases

Every node matches

prev never leaves the dummy. Each pass removes the new first node, and dummy.next ends as null.

val is 0 or larger than every value

Node values are at least 1, so val = 0 matches nothing. The walk only steps forward and returns the list unchanged.

07

Complexity

Time
O(n)
Space
O(1)
Each pass of the loop either removes one node or moves prev past one node, so there are at most n passes. Up to 10⁴ nodes is small for one walk.
08

Remove Linked List Elements FAQ

Is there a recursive solution?

Yes: clean the rest of the list first with head.next = removeElements(head.next, val), then return head.next if head matches, else head. It is three lines but keeps one stack frame per node, up to 10⁴ deep.

Can I do it without a dummy node?

Yes. First move head forward while it matches, then run the same look-ahead loop from the new head. It works, but the head case is written twice, which is the duplication the dummy avoids.

How is this different from deleting a node when only that node is given?

In Delete Node in a Linked List you have no access to the node before, so you copy the next value over and delete the next node instead. Here you have the head, so you can always reach the node before.