← All problems

3217. Delete Nodes from Linked List Present in Array

MediumOpen on LeetCodeProblem statement

Problem Statement

3217. Delete Nodes From Linked List Present in Array

Medium


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:

Java

Source file
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode modifiedList(int[] nums, ListNode head) {
    Set<Integer> del = Arrays.stream(nums).boxed().collect(Collectors.toCollection(HashSet::new));
        ListNode curr = head, dummy = new ListNode(0, head), prev = dummy;
        while(curr!=null){
            while(curr!=null && del.contains(curr.val))
                curr = curr.next;
            prev.next = curr;
            if(curr==null)
                break;
            curr = curr.next;
            prev = prev.next;
        }
        return dummy.next;
    }
}