Skip to main content
Back to problems
#3217
Medium Algorithms

Delete nodes from linked list present in array

Array Hash Table Linked List
69.5% acceptance
Feb 23, 2026
1083
50
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn modified_list(nums: Vec<i32>, head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let banned: std::collections::HashSet<i32> = nums.into_iter().collect();
    let mut dummy = Box::new(ListNode { val: 0, next: head });
    let mut cur = &mut dummy;
    while let Some(ref mut node) = cur.next {
      if banned.contains(&node.val) {
        // Remove this node
        cur.next = node.next.take();
      } else {
        cur = cur.next.as_mut().unwrap();
      }
    }
    dummy.next
  }
}