Delete Nodes From Linked List Present in Array - Problem

You're given an array of integers nums containing values that need to be filtered out from a linked list. Your task is to traverse the linked list and remove all nodes whose values appear anywhere in the nums array.

Think of it as having a blacklist of values - any node in the linked list matching a value from this blacklist should be deleted. The challenge is to do this efficiently while maintaining the structure of the remaining linked list.

Goal: Return the head of the modified linked list after removing all blacklisted nodes.

Input: An array nums and the head of a singly linked list

Output: The head of the filtered linked list

Input & Output

example_1.py โ€” Basic Filtering
$ Input: nums = [1,2,3], head = [1,2,3,4,5]
โ€บ Output: [4,5]
๐Ÿ’ก Note: Remove nodes with values 1, 2, and 3 from the linked list, leaving only nodes 4 and 5
example_2.py โ€” Remove All Nodes
$ Input: nums = [1], head = [1,1,1,1]
โ€บ Output: []
๐Ÿ’ก Note: All nodes have value 1 which exists in nums, so the entire list is removed
example_3.py โ€” Remove None
$ Input: nums = [5], head = [1,2,3,4]
โ€บ Output: [1,2,3,4]
๐Ÿ’ก Note: None of the list values (1,2,3,4) appear in nums [5], so all nodes are kept

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 105
  • The number of nodes in the given list is in the range [1, 105]
  • 1 โ‰ค Node.val โ‰ค 105
  • The input is generated such that there is at least one node in the linked list that has a value not present in nums

Visualization

Tap to expand
๐Ÿ›ก๏ธ Security Checkpoint Filtering๐Ÿ“‹ Blacklistโ€ข Person ID: 1โ€ข Person ID: 2โ€ข Person ID: 3๐Ÿ‘ฎSecurity GuardMemorized ListBefore: People in Queue1245After: Filtered Queue45โœ“ Safe to proceedO(1) RecognitionโŒ Removed: IDs 1, 2, 3
Understanding the Visualization
1
Memorize Blacklist
Security guard studies the blacklist and memorizes all banned individuals (build hash set)
2
Process Queue
As people walk through, guard instantly recognizes blacklisted individuals and removes them
3
Maintain Order
Non-blacklisted people continue through in their original order
Key Takeaway
๐ŸŽฏ Key Insight: Converting the blacklist to a hash set transforms slow O(n) searches into instant O(1) lookups, making the entire filtering process much more efficient!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.5K Views
High Frequency
~18 min Avg. Time
1.8K 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