Skip to content
Problem 203 · LeetCode 203(opens in a new tab)

Remove Linked List Elements

EasyLinked lists

You get the head of a singly linked list and a number val. Take out every node whose value equals val, keep the other nodes in their original order, and return the head of what is left.

The head itself may need to go, and so may every node; in that case return an empty list.

Example 1

Input:  head = [4, 9, 9, 2, 9], val = 9
Output: [4, 2]
Why:    all three 9s go, including the two in a row
2 more examples and the constraints

Example 2

Input:  head = [], val = 3
Output: []
Why:    there is nothing to remove

Example 3

Input:  head = [5, 5, 5], val = 5
Output: []
Why:    every node matches, the head too

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • 1 ≤ each node's value ≤ 50
  • 0 ≤ val ≤ 50

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Fix the head, then the restO(n)
  2. Dummy head, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
Fix the head, then the restO(n)
Correct; needs a special case
Dummy head, one passO(n)
Best; one loop, no special case

n = number of nodes. Both are linear with O(1) memory; the dummy removes the special case.

Edge cases to test

  • Empty list. Return null right away; the loop never runs.
  • The head matches. [6, 1, 2] with val 6: the dummy makes this the same as any other removal.
  • Matches in a row. [4, 9, 9, 2]: after unlinking one 9, cur must stay to check the next.
  • Every node matches. [5, 5, 5] with val 5 returns an empty list.
  • val not present. The list comes back unchanged.

Common mistakes

  • Moving cur forward right after unlinking, which skips the second of two matches in a row.
  • Returning head instead of dummy.next, so a removed head comes back.
  • Handling the head with a single if instead of a loop, which fails when several leading nodes match.

How to talk through it

  1. 1Clarify. Can the list be empty? Can the head match? Should the kept nodes stay in order?
  2. 2Say what removal needs. To drop a node you change the next of the node before it.
  3. 3Add the dummy. A spare node in front gives the head a predecessor, so there is no special case.
  4. 4Walk the loop. Unlink and stay on a match; move on otherwise. A recursive version works too, at O(n) stack.
  5. 5Test out loud. Run the empty list, all nodes matching, and two matches in a row.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?