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
.
Example 1:
nums = [1,2,3], head = [1,2,3,4,5]
Output: [4,5]
Remove the nodes with values 1, 2, and 3.
Example 2:
nums = [1], head = [1,2,1,2,1,2]
Output: [2,2,2]
Remove the nodes with value 1.
Example 3:
nums = [5], head = [1,2,3,4]
Output: [1,2,3,4]
No node has value 5.
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
nums
are unique.[1, 10^5]
.1 <= Node.val <= 10^5
nums
.The most straightforward way to solve this problem is to iterate through the linked list and, for each node, check if its value exists in the nums
array. If it does, remove the node. This involves nested iterations, leading to a less efficient solution.
current
pointer.nums
array.current.val
is found in nums
, remove the node from the linked list.def remove_nodes_naive(nums, head):
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next:
if current.next.val in nums:
current.next = current.next.next
else:
current = current.next
return dummy.next
nums
array, due to the nested loops.To improve efficiency, we can use a hash set (or set in Python) to store the values from the nums
array. This allows for O(1) lookup time, reducing the overall time complexity.
nums
array into a hash set for quick lookups.current
pointer.current.next.val
is in the hash set, remove the node.current
pointer to the next node.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_nodes(nums, head):
num_set = set(nums)
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next:
if current.next.val in num_set:
current.next = current.next.next
else:
current = current.next
return dummy.next
nums
array. The O(M) comes from building the set. The iteration through the linked list is O(N).nums
array, due to the space used by the hash set.None
.nums
Array: If the nums
array is empty, no nodes should be removed, and the original linked list should be returned.nums
, the function should return an empty linked list.Here's the code with edge cases considered:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def remove_nodes(nums, head):
num_set = set(nums)
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next:
if current.next.val in num_set:
current.next = current.next.next
else:
current = current.next
return dummy.next