Remove Linked List Elements
Easy · Linked Lists · Linked List · Recursion
Problem
Given the head of a linked list and an integer val, delete every node whose value equals val and return the new head. The head itself may need to be removed, possibly several times in a row, and the list may become empty.
The tests build lists with from_list([...]) and read your answer back with to_list(), both already defined.
Examples
Input: head = 6 -> 2 -> 6 -> 3 -> 6, val = 6 Output: 2 -> 3
All three 6 nodes, including the head, are removed.
Input: head = 4 -> 4, val = 4 Output: (empty)
Every node matches, so the list becomes empty.
Input: head = 1 -> 2 -> 3, val = 9 Output: 1 -> 2 -> 3
Nothing matches; the list is unchanged.
Constraints
- 0 <= number of nodes <= 10^4
- 1 <= Node.val <= 50
- 0 <= val <= 50
Approaches
- Baseline: remove one match at a time from the front — time O(n · k), space O(1)
Follow-up
What if the list were unsorted and the rule were “remove every value seen before”? The fate of a node then depends on earlier nodes; keep a set of seen values (see the use case “Keep only the first copy of each value”).
Related problems
Start free on Cariara · Coding problems · System design studio