Delete Nodes From Linked List Present in Array - Problem

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.

The linked list is represented as a sequence of nodes where each node contains an integer value and a pointer to the next node. After removal, the remaining nodes should maintain their original relative order.

Input & Output

Example 1 — Basic Deletion
$ Input: nums = [1,2,3], head = [1,2,3,4,5]
Output: [4,5]
💡 Note: Remove nodes with values 1, 2, 3 from the linked list. Only nodes with values 4 and 5 remain.
Example 2 — Partial Deletion
$ Input: nums = [1], head = [1,2,1,2,1,2]
Output: [2,2,2]
💡 Note: Remove all nodes with value 1. The three nodes with value 2 remain in their original order.
Example 3 — No Deletion
$ Input: nums = [5], head = [1,2,3,4]
Output: [1,2,3,4]
💡 Note: No nodes have value 5, so the entire linked list remains unchanged.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 105
  • The number of nodes in the linked list is in the range [1, 105]
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
Delete Nodes From Linked List Present in Array INPUT nums = [1, 2, 3] (values to delete) 1 2 3 Linked List (head) 1 2 3 4 5 To Delete To Keep nums = [1, 2, 3] head = [1,2,3,4,5] ALGORITHM STEPS 1 Build Hash Set Add nums to HashSet Set{1, 2, 3} 2 Create Dummy Node Handle head removal D 1 3 Traverse List Check each node in Set if val in Set: skip node else: keep node 4 Return Result dummy.next = new head Time: O(n+m) | Space: O(m) FINAL RESULT Nodes Removed: 1 2 3 Modified Linked List: 4 5 NULL Output: [4, 5] OK - Order Preserved Relative order maintained Key Insight: Using a Hash Set for O(1) lookup transforms naive O(n*m) approach to O(n+m). A dummy node simplifies edge cases when head itself needs deletion. Just check: is current.next.val in Set? TutorialsPoint - Delete Nodes From Linked List Present in Array | Hash Set Optimization
Asked in
Amazon 15 Microsoft 12 Google 8
28.5K Views
Medium Frequency
~15 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen