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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code