LeetCode Challenge Day 47 β 3217. Delete Nodes From Linked List Present in Array
Nitin Ahirwal / November 1, 2025
Hey folks π
This is Day 47 of my LeetCode streak π
Todayβs problem is 3217. Delete Nodes From Linked List Present in Array β a medium-level linked list problem that focuses on efficiently removing nodes based on an array of values.
π Problem Statement
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 whose values exist in nums.
Example 1:
Input: nums = [1,2,3], head = [1,2,3,4,5]
Output: [4,5]
Example 2:
Input: nums = [1], head = [1,2,1,2,1,2]
Output: [2,2,2]
Example 3:
Input: nums = [5], head = [1,2,3,4]
Output: [1,2,3,4]
π‘ Intuition
The key insight is that repeatedly checking if a nodeβs value exists in nums could be slow if we use an array lookup.
To make this efficient, we can store all elements of nums in a Set, allowing for O(1) lookups when determining whether a node should be deleted.
π Approach
- Convert the array
numsinto a Set for constant-time value lookup. - Create a dummy node that points to the head β this simplifies removal of the head node when necessary.
- Traverse the linked list using a pointer
current.- If
current.next.valexists in the set, skip the node (current.next = current.next.next). - Otherwise, move to the next node.
- If
- Continue until all nodes are processed.
- Return
dummy.nextas the new head of the modified list.
β±οΈ Complexity Analysis
-
Time complexity:
(O(n + m)) β wherenis the number of linked list nodes andmis the number of elements innums. -
Space complexity:
(O(m)) β for storingnumsin a Set.
π§βπ» Code (JavaScript)
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {number[]} nums
* @param {ListNode} head
* @return {ListNode}
*/
var modifiedList = function(nums, head) {
const removeSet = new Set(nums);
const dummy = new ListNode(0, head);
let current = dummy;
while (current.next) {
if (removeSet.has(current.next.val)) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return dummy.next;
};
π§ͺ Example Walkthrough
Input:
nums = [1,2,3], head = [1,2,3,4,5]
Steps:
- Convert nums β 3
- Start with dummy β 0 β 1 β 2 β 3 β 4 β 5
- Remove 1, 2, and 3 since they exist in the Set
- Remaining list: 4 β 5
β Output = [4,5]
π― Reflection
This problem highlights how hash-based lookups and a dummy node pattern can simplify linked list manipulation. Itβs an elegant one-pass solution thatβs both clean and efficient β a must-know technique for any linked list problem!
Thatβs it for Day 47 of my LeetCode journey πͺ See you tomorrow for Day 48 β letβs keep building consistency and clarity in problem-solving! π₯
Happy Coding π¨βπ»