#3217
Delete Nodes From Linked List Present in Array
MediumArrayHash TableLinked ListHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a set to store the values from the array, allowing for O(1) average time complexity for lookups. We then iterate through the linked list just once, removing nodes as needed.
⚙️
Algorithm
3 steps- 1Step 1: Convert the array nums into a set for O(1) lookups.
- 2Step 2: Initialize a dummy node to simplify edge cases and maintain the head of the modified list.
- 3Step 3: Iterate through the linked list, checking if each node's value is in the set. If it is, skip it; otherwise, link it to the new list.
solution.py18 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def deleteNodes(nums, head):
8 num_set = set(nums)
9 dummy = ListNode(0)
10 prev = dummy
11 current = head
12 while current:
13 if current.val not in num_set:
14 prev.next = current
15 prev = current
16 current = current.next
17 prev.next = None # Terminate the list
18 return dummy.nextℹ
Complexity note: The time complexity is O(n) because we traverse the linked list once, and the space complexity is O(n) due to the set storing the values from the array.
- 1Using a set allows for efficient lookups, significantly improving performance.
- 2Iterating through the linked list only once is key to achieving optimal time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.