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 Arraynums = [1,2,3]123Linked List:12345DELETEDELETEDELETEKEEPKEEPRemove nodes with values present in nums arrayResult:45
Understanding the Visualization
1
Input
Array nums=[1,2,3] and linked list [1,2,3,4,5]
2
Filter
Remove nodes whose values exist in nums array
3
Output
Remaining linked list [4,5] maintains original order
Key Takeaway
🎯 Key Insight: Hash set enables O(1) lookups instead of O(m) array scans, transforming O(n×m) to O(n+m)
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