Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 1, 2025 22:18
Show Gist options
  • Select an option

  • Save Ifihan/4af5cf9e7155a4b73bc3161116920c9a to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/4af5cf9e7155a4b73bc3161116920c9a to your computer and use it in GitHub Desktop.
Delete Nodes From Linked List Present in Array

Question

Approach

I first convert nums into a set for O(1) lookups. Then, I use a dummy node to simplify edge cases like when the head itself needs to be removed. I traverse the linked list with a pointer. If the current node’s value is in the set, I skip it by linking to curr.next; otherwise, I move forward. Finally, I return dummy.next as the new head of the modified list.

Implementation

class Solution:
    def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]:
        remove = set(nums)
        dummy = ListNode(0)
        dummy.next = head
        curr = dummy
        
        while curr.next:
            if curr.next.val in remove:
                curr.next = curr.next.next
            else:
                curr = curr.next
                
        return dummy.next

Complexities

  • Time: O(n + m), where n is the number of nodes and m is the size of nums
  • Space: O(m)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment