3217. Delete Nodes From Linked List Present in Array
Difficulty: Medium
Topics: Array, Hash Table, Linked List
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:
Remove the nodes with values 1, 2, and 3.Example 2:
Remove the nodes with value 1.Example 3:
No node has value 5.Constraints:
Hint:
Solution:
We need to traverse through the linked list and remove any nodes that have a value present in the array nums.
Let's implement this solution in PHP: 3217. Delete Nodes From Linked List Present in Array
val = $val;
$this->next = $next;
}
}
class Solution {
/**
* @param Integer[] $nums
* @param ListNode $head
* @return ListNode
*/
function removeElements($head, $nums) {
...
...
...
/**
* go to ./solution.php
*/
}
}
// Example usage:
// Linked List: 1 -> 2 -> 3 -> 4 -> 5
$head = new ListNode(1);
$head->next = new ListNode(2);
$head->next->next = new ListNode(3);
$head->next->next->next = new ListNode(4);
$head->next->next->next->next = new ListNode(5);
// Array nums: [1, 2, 3]
$nums = [1, 2, 3];
$solution = new Solution();
$result = $solution->removeElements($head, $nums);
// Function to print the linked list
function printList($node) {
while ($node !== null) {
echo $node->val . " ";
$node = $node->next;
}
}
// Print the resulting linked list
printList($result); // Output: 4 5
?>
Explanation:
-
removeElements($head, $nums):
- We first convert nums into a hash set ($numSet = array_flip($nums);) for fast lookups.
- A dummy node is created and linked to the head of the list. This helps simplify edge cases like removing the head node.
- The prev pointer tracks the node before the current one, allowing us to remove the current node by skipping it in the list.
- For each node, we check if its value is in numSet. If so, we remove it by adjusting the prev->next pointer to skip the current node.
-
Edge Cases:
- If the head node needs to be removed, the dummy node ensures the head can be cleanly removed and still return the correct list.
- Handles cases where multiple consecutive nodes need to be removed.
-
Complexity:
-
Time Complexity: O(n), where n is the number of nodes in the linked list. We visit each node once. Converting nums to a set takes O(m), where m is the size of nums.
-
Space Complexity: O(m) for storing the nums set.
Example Walkthrough:
For input nums = [1, 2, 3] and head = [1, 2, 3, 4, 5], the algorithm will:
The resulting linked list is [4, 5].
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Delete Nodes From Linked List Present in Array. For more information, please follow other related articles on the PHP Chinese website!