Delete Nodes From Linked List Present in Array Problem
#3217
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3217.
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 all nodes from the linked list that have a value that exists in nums.
Example 1:
Input: nums = [1,2,3], head = [1,2,3,4,5]
Output: [4,5]
Explanation:

Remove the nodes with values 1, 2, and 3.
Example 2:
Input: nums = [1], head = [1,2,1,2,1,2]
Output: [2,2,2]
Explanation:

Remove the nodes with value 1.
Example 3:
Input: nums = [5], head = [1,2,3,4]
Output: [1,2,3,4]
Explanation:

No node has value 5.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5- All elements in
numsare unique. - The number of nodes in the given list is in the range
[1, 10^5]. 1 <= Node.val <= 10^5- The input is generated such that there is at least one node in the linked list that has a value not present in
nums.
Solution
Approach: Hash Set
Put all values of nums into a hash set. Add a dummy node in front of head, then walk the list: if the next node's value is in the set, unlink it; otherwise step forward. The answer is the dummy's next node.
Complexity: time O(n + m), space O(n), where n is the length of nums and m is the length of the list.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def modifiedList(
self, nums: List[int], head: Optional[ListNode]
) -> Optional[ListNode]:
s = set(nums)
pre = dummy = ListNode(next=head)
while pre.next:
if pre.next.val in s:
pre.next = pre.next.next
else:
pre = pre.next
return dummy.next