Sponsored
Sponsored
This approach uses a set for fast lookup of values that need to be removed from the linked list. By iterating through the linked list and checking if each node's value is in the set, we can efficiently determine which nodes to skip and which to keep.
Time Complexity: O(N + M), where N is the length of the linked list and M is the size of nums.
Space Complexity: O(M), where M is the size of nums.
1function ListNode(val, next = null) {
2 this.val = val;
3 this.next = next;
4}
5
6function deleteNodes(head, nums) {
7 const lookup = new Set(nums);
8 let dummy = new ListNode(0);
9 dummy.next = head;
10 let prev = dummy, current = head;
11
12 while (current) {
13 if (lookup.has(current.val)) {
14 prev.next = current.next;
15 } else {
16 prev = current;
17 }
18 current = current.next;
19 }
20
21 return dummy.next;
22}
In JavaScript, a Set
helps in quick lookup of node values that need to be deleted. The solution handles deletions by maintaining a previous reference node, allowing efficient removal of target nodes from the linked list.
This approach leverages a two-pointer technique where the result is constructed in-place. Although it doesn't require extra storage for the set, it does involve modifications that make subsequent operations more complex in favor of reducing space usage.
Time Complexity: O(N * M), where N is the length of the linked list and M is the size of nums.
Space Complexity: O(1).
The Java solution also implements a direct array search within isInArray
, emphasizing zero additional storage beyond simple node pointer management.