Delete Nodes From Linked List Present in Array (LeetCode 3217): Solution and Explanation
Given an array nums and the head of a linked list, remove every node whose value is in nums and return the new head. At least one node always survives.
Intuition
Each node faces one question: is my value in nums? Scanning nums for every node costs O(n * m), which is too slow at 10^5 each. A hash set built once answers the question in O(1).
Unlinking a node in a singly linked list means changing the next of the node before it. So the walker cur should stand on a kept node and look one step ahead at cur.next.
The head may need to go too, and it has no node before it. A dummy node placed in front of head gives it one, so the head needs no special case.
After an unlink, cur must not move: the node that slid into cur.next has not been checked yet. That is how runs of consecutive banned nodes disappear one after another.
Approach: Hash set plus dummy node sweep
- Build
banned = set(nums). - Create
dummywithdummy.next = headand setcur = dummy. - While
cur.nextis not null: ifcur.next.valis inbanned, setcur.next = cur.next.next; otherwise movecur = cur.next. - Return
dummy.next.
Step-by-step example
nums = [1,2,3], head = [1,2,3,4,5]
- banned = {1,2,3}. cur starts on the dummy, whose next is 1.
- 1 is banned: dummy.next becomes 2. cur stays on the dummy.
- 2 is banned: dummy.next becomes 3. 3 is banned: dummy.next becomes 4.
- 4 is not banned, so cur moves to 4. 5 is not banned, so cur moves to 5.
- cur.next is null. Return dummy.next, which is [4,5].
Code: Python, Java, C++
1class Solution:
2 def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]:
3 banned = set(nums)
4 dummy = ListNode(0, head)
5 cur = dummy
6 while cur.next:
7 if cur.next.val in banned:
8 cur.next = cur.next.next
9 else:
10 cur = cur.next
11 return dummy.next1class Solution {
2 public ListNode modifiedList(int[] nums, ListNode head) {
3 Set<Integer> banned = new HashSet<>();
4 for (int x : nums) banned.add(x);
5 ListNode dummy = new ListNode(0, head);
6 ListNode cur = dummy;
7 while (cur.next != null) {
8 if (banned.contains(cur.next.val)) {
9 cur.next = cur.next.next;
10 } else {
11 cur = cur.next;
12 }
13 }
14 return dummy.next;
15 }
16}1class Solution {
2public:
3 ListNode* modifiedList(vector<int>& nums, ListNode* head) {
4 unordered_set<int> banned(nums.begin(), nums.end());
5 ListNode dummy(0);
6 dummy.next = head;
7 ListNode* cur = &dummy;
8 while (cur->next) {
9 if (banned.count(cur->next->val)) {
10 cur->next = cur->next->next;
11 } else {
12 cur = cur->next;
13 }
14 }
15 return dummy.next;
16 }
17};Time and space complexity
O(n + m)
Building the set takes O(m) for m values in nums, and each of the n nodes is checked once with an O(1) lookup.
O(m)
The hash set holds the m values of nums. The list itself is changed in place.
Other approaches
Boolean array instead of a set (time O(n + m), space O(max value))
Values are at most 10^5, so a boolean array of that size works as a faster set. Same idea, fixed memory of about 10^5 flags.
Scan nums for every node (time O(n * m), space O(1))
Check each node with a linear search through nums. Correct, but O(n * m) and too slow at the upper limits.
Rebuild into a new list (time O(n + m), space O(n + m))
Copy every kept value into fresh nodes. Simple, but allocates a second list for no benefit.
Common mistakes
- Advancing
curright after an unlink. If two banned nodes are adjacent, the second one is skipped over and survives. - Handling a banned head with a separate loop and forgetting the general case afterwards. The dummy node avoids both.
- Searching the array
numsfor every node, which turns the solution quadratic. - Returning
headinstead ofdummy.next. When the original head was removed,headstill points at a deleted node.
Frequently asked questions
Why does cur look at cur.next instead of standing on the node it checks?
In a singly linked list you can only unlink a node from the node before it. Keeping cur one step behind the node being checked means the unlink is a single assignment.
Can the result be empty?
Not for this problem. The constraints promise that at least one node has a value missing from nums, so the answer always has at least one node. The code would still return null correctly if it were empty.
How is this different from Remove Linked List Elements?
That problem removes one value; this one removes any value from a set. The sweep is identical, only the test changes from an equality check to a set lookup.