LeetCode 3217: Delete Nodes From Linked List Present in Array Solution

Master LeetCode problem 3217 (Delete Nodes From Linked List Present in Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3217. Delete Nodes From Linked List Present in Array

Problem Explanation

Explanation

To solve this problem, we can iterate through the linked list while keeping track of the nodes that need to be deleted. We can use a HashSet to store the values from the given array for efficient lookups. While iterating through the linked list, if we encounter a node with a value that exists in the HashSet, we skip that node by updating the previous node's next pointer. At the end, we return the head of the modified linked list.

  • Time complexity: O(N) where N is the number of nodes in the linked list.
  • Space complexity: O(M) where M is the number of distinct values in the array.

Solution Code

public ListNode deleteNodesFromLinkedList(int[] nums, ListNode head) {
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode prev = dummy;
    ListNode curr = head;
    
    while (curr != null) {
        if (set.contains(curr.val)) {
            prev.next = curr.next;
        } else {
            prev = curr;
        }
        curr = curr.next;
    }
    
    return dummy.next;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3217 (Delete Nodes From Linked List Present in Array)?

This page provides optimized solutions for LeetCode problem 3217 (Delete Nodes From Linked List Present in Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3217 (Delete Nodes From Linked List Present in Array)?

The time complexity for LeetCode 3217 (Delete Nodes From Linked List Present in Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3217 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3217 in Java, C++, or Python.

Back to LeetCode Solutions