Delete Nodes From Linked List Present in Array

You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing every node whose value appears in nums.

30:00

Delete Nodes From Linked List Present in Array
medium
Free written solution
Topics
Companies

You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing every node whose value appears in nums.

Example 1:
Input: {"nums":[1,2,3],"head":[1,2,3,4,5]}
Output: [4,5]
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1051 \leq \text{nums[i]} \leq 10^5

  • All elements in nums are unique.

  • The number of nodes in the list is in the range [1,105][1, 10^5].

  • 1≤Node.val≤1051 \leq \text{Node.val} \leq 10^5

  • At least one node in the list has a value not present in nums.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3],"head":[1,2,3,4,5]}

Load nums into a hash set {1,2,3}. Now "should this node go?" is one O(1) lookup instead of a scan of nums.

banned = set(nums)

1
2
3
▼ cur: last kept node□ cur.next: node being checked✕ unlinked
nulldummy1021324354

Kept so far: 0, unlinked: 0, still to check: 5

[1, 2, 3, 4, 5]

Variables
VariableValue
banned{1,2,3}
curdummy
cur.next-
removed0
DepthFunction Call
Stack empty
0/13