The Delete Nodes From Linked List Present in Array interview question involves filtering a linear data structure based on a set of prohibited values. You are given the head of a linked list and an array of integers. Your goal is to remove every node from the list whose value exists in the given array. This Delete Nodes From Linked List Present in Array coding problem is a fundamental test of combining multiple data structures for efficiency.
Companies like Microsoft and Amazon ask this to see if you can optimize a search operation. If you check the array for every node in the list using a linear search, the time complexity becomes , where is the list length and is the array size. Interviewers want to see you use a Hash Table interview pattern to reduce this to .
This problem uses a Hash Set for lookups combined with a Linked List Traversal.
next node's value is in the set.Suppose the list is 10 -> 20 -> 30 -> 40 and the array is [20, 40].
[20, 40] into a set.10.10: Not in set. Move to 10.20: IN SET! Change 10.next to point to 30.30: Not in set. Move to 30.40: IN SET! Change 30.next to null.
Final List: 10 -> 30.Always use a Dummy Node when you need to delete nodes from a linked list. It simplifies the logic significantly by ensuring the node you are deleting always has a "previous" node to link from, even if it's the very first element.