Delete Nodes From Linked List Present in Array

Medium Topics Company Tags

Remove every node whose value appears in nums, and return the head of the remaining linked list. Keep the surviving nodes in their original order. The values in nums are distinct, and at least one list node is guaranteed to survive. Arrays used for head in the examples and test inputs show node values from head to tail.

Filled nodes in the input diagram are removed.

Example 1:

Delete Nodes From Linked List Present in Array, example 1: illustration of the example

Input: nums = [2,4]
head = [1,2,3,4,2,5]

Output: [1,3,5]

Explanation: Remove every occurrence of 2 and 4. The surviving nodes form 1 -> 3 -> 5 in their original order.

Example 2:

Delete Nodes From Linked List Present in Array, example 2: illustration of the example

Input: nums = [7]
head = [7,8,7,8]

Output: [8,8]

Explanation: Both nodes containing 7 are removed. Both nodes containing 8 remain, including their repeated value.

Example 3:

Delete Nodes From Linked List Present in Array, example 3: illustration of the example

Input: nums = [3,9]
head = [1,2]

Output: [1,2]

Explanation: Neither 3 nor 9 appears in the linked list, so no nodes are removed.

Constraints:

  • 1 <= nums.length <= 100000
  • The list contains between 1 and 100000 nodes.
  • All array and node values are between 1 and 100000.
  • The values in nums are distinct.
  • At least one node has a value that is absent from nums.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.