Delete Matching Nodes from a Singly Linked List

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Design an in-place routine for a singly linked list of integers that deletes every node storing a specified integer target and returns the front node of the updated chain.

target can show up anywhere in the chain—at the beginning, in consecutive clusters, at the tail, across every single node, or nowhere at all—and the input chain may be empty. Unlink matching nodes directly by updating next references in O(1) auxiliary memory instead of allocating a second chain of nodes.

For automated grading, implement remove_target_values(values: List[int], target: int) -> List[int], which converts values into a singly linked list, executes your in-place pointer deletion on that chain, and returns the surviving node values in order.

Examples

Example 1

Input: values = [8, 3, 8, 5, 2, 8], target = 8
Output: [3, 5, 2]

Walk-through: Starting from 8 -> 3 -> 8 -> 5 -> 2 -> 8, unlinking the leading, interior, and trailing 8 nodes rewires the chain into 3 -> 5 -> 2.

Example 2

Input: values = [4, 4, 4, 4], target = 4
Output: []

Walk-through: Every node holds 4, so all four nodes are unlinked and the resulting chain is empty (None, serialized as []).

Example 3

Input: values = [10, -2, 7], target = 5
Output: [10, -2, 7]

Walk-through: None of the nodes equal 5, so every pointer stays unchanged and [10, -2, 7] is returned intact.

Constraints

  • 0 <= len(values) <= 10^4
  • -10^9 <= values[i], target <= 10^9
  • Core linked-list removal must run in O(n) time and O(1) extra space (excluding the O(n) conversion from and to List[int] in the test wrapper).

Step-by-step walkthrough

  1. Understand the problem and the judge adapter

    Starting from the front node head of a singly linked list (a linear chain where each node holds an integer val and a forward reference next), we need to unlink every node storing target in place—rewiring existing next pointers with O(1) extra space instead of constructing a second node chain—and return the updated front node.

    Because the test runner calls remove_target_values(values, target) with plain Python lists, we separate the implementation cleanly into three small functions:

    1. build_linked_list(values) builds a ListNode chain from the input numbers,
    2. remove_elements(head, target) executes the genuine O(1)-space in-place pointer deletion, and
    3. linked_list_to_values(new_head) collects the surviving node values back into a Python list.
  2. Why deleting the head node is tricky without help

    Unlinking an interior node current from a singly linked list requires standing on the node right before it (prev) so you can redirect prev.next to current.next:

    Unlinking 8 from the interior (prev = 3, current = 8):
    
      Before:   [3] -> [8] -> [5]
                prev  current
    
      Rewire:   [3] --------> [5]    (prev.next = current.next)
    

    That rule works everywhere except at head, because no node precedes head! Without extra help, you would have to write a dedicated while loop at the start just to peel off matching front nodes (such as [4, 4, 4, 4] with target = 4), check whether the entire chain vanished (None), and then run a second loop on the tail. Duplicating deletion logic in two loops invites off-by-one and null-dereference bugs.

  3. Key idea: add a dummy sentinel node in front of head

    We eliminate the front-node special case by placing one temporary dummy (sentinel) node ahead of head with dummy.next = head:

      [dummy] -> [4] -> [4] -> [9] -> None
        ^         ^
       prev     head (now has a predecessor just like every interior node!)
    

    With dummy in front, every real node—including the original head—is reached via prev.next from a predecessor node prev! Once the traversal ends, dummy.next automatically points to the new front node (or None when every node matched target). Because our loop only inspects prev.next, dummy.val (0) is never tested against target.

  4. Unlink matching nodes without skipping consecutive matches

    Initialize prev = dummy and inspect current = prev.next while prev.next is not None:

    • When current.val == target: bypass current via prev.next = current.next. Crucially, keep prev where it is! Because current.next just moved into prev.next, we have not checked its value yet—it could equal target as well!
    • When current.val != target: current survives, so step prev forward onto current.
    Why prev MUST stay put after unlinking (target = 4):
    
      Step 1:  [dummy] -> [1] -> [4] -> [4] -> [2] -> None
                          prev  current
    
      Unlink first 4 (prev.next = current.next), keep prev at [1]:
               [dummy] -> [1] --------> [4] -> [2] -> None
                          prev        new prev.next (inspected next!)
    
      Advancing prev right away would leap over the second [4]!
    
    class ListNode:
        """Single node in a singly linked list: stores val and a next pointer."""
    
        def __init__(self, val: int, next: Optional["ListNode"] = None):
            self.val = val
            self.next = next
    
    
    def remove_elements(head: Optional[ListNode], target: int) -> Optional[ListNode]:
        """Unlink every node with val == target in place and return the new head."""
        # dummy: sentinel node placed before head (dummy -> head -> ...) so even
        # the original head has a predecessor node we can rewire safely.
        dummy = ListNode(0, head)
        prev = dummy
    
        # Inspect the node right after prev on each step until we reach the end.
        while prev.next is not None:
            current = prev.next
            if current.val == target:
                # Bypass current in place. Do NOT advance prev here, because the
                # new prev.next node has not been checked yet and may also match!
                prev.next = current.next
            else:
                # current survives, so advance prev onto current.
                prev = current
    
        # dummy.next is the surviving head, or None if all nodes were removed.
        return dummy.next
    
  5. Trace Example 1 and Example 2, and wire up the judge helpers

    Let's walk dummy and prev across Examples 1 and 2:

    Example 1: values = [8, 3, 8, 5, 2, 8], target = 8
      Start: [dummy] -> 8 -> 3 -> 8 -> 5 -> 2 -> 8 -> None   (prev = dummy)
      8 == 8 -> rewire dummy.next = 3 (prev stays at dummy)
      3 != 8 -> advance prev to 3
      8 == 8 -> rewire 3.next = 5     (prev stays at 3)
      5 != 8 -> advance prev to 5
      2 != 8 -> advance prev to 2
      8 == 8 -> rewire 2.next = None  (prev stays at 2)
      prev.next is None -> stop! Return dummy.next -> [3, 5, 2]
    
    Example 2: values = [4, 4, 4, 4], target = 4
      Start: [dummy] -> 4 -> 4 -> 4 -> 4 -> None   (prev = dummy)
      Pass 1: 4 == 4 -> dummy.next = second 4 (prev stays at dummy)
      Pass 2: 4 == 4 -> dummy.next = third 4  (prev stays at dummy)
      Pass 3: 4 == 4 -> dummy.next = fourth 4 (prev stays at dummy)
      Pass 4: 4 == 4 -> dummy.next = None     (prev stays at dummy)
      prev.next is None -> stop! Return dummy.next = None -> []
    

    Next we connect the serialization helpers for remove_target_values:

    def build_linked_list(values: List[int]) -> Optional[ListNode]:
        """Convert the judge's Python list of ints into a chain of ListNode objects."""
        dummy = ListNode(0)
        tail = dummy
        for value in values:
            tail.next = ListNode(value)
            tail = tail.next
        return dummy.next
    
    
    def linked_list_to_values(head: Optional[ListNode]) -> List[int]:
        """Read node values from head to None back into a Python list for the judge."""
        result: List[int] = []
        node = head
        while node is not None:
            result.append(node.val)
            node = node.next
        return result
    
    
    def remove_target_values(values: List[int], target: int) -> List[int]:
        # Build the linked list, perform the in-place pointer removal, and serialize.
        head = build_linked_list(values)
        new_head = remove_elements(head, target)
        return linked_list_to_values(new_head)
    
  6. Complete solution

    Here is the complete implementation ready to submit:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class ListNode:
        """Single node in a singly linked list: stores val and a next pointer."""
    
        def __init__(self, val: int, next: Optional["ListNode"] = None):
            self.val = val
            self.next = next
    
    
    def remove_elements(head: Optional[ListNode], target: int) -> Optional[ListNode]:
        """Unlink every node with val == target in place and return the new head."""
        # dummy: sentinel node placed before head (dummy -> head -> ...) so even
        # the original head has a predecessor node we can rewire safely.
        dummy = ListNode(0, head)
        prev = dummy
    
        # Inspect the node right after prev on each step until we reach the end.
        while prev.next is not None:
            current = prev.next
            if current.val == target:
                # Bypass current in place. Do NOT advance prev here, because the
                # new prev.next node has not been checked yet and may also match!
                prev.next = current.next
            else:
                # current survives, so advance prev onto current.
                prev = current
    
        # dummy.next is the surviving head, or None if all nodes were removed.
        return dummy.next
    
    
    def build_linked_list(values: List[int]) -> Optional[ListNode]:
        """Convert the judge's Python list of ints into a chain of ListNode objects."""
        dummy = ListNode(0)
        tail = dummy
        for value in values:
            tail.next = ListNode(value)
            tail = tail.next
        return dummy.next
    
    
    def linked_list_to_values(head: Optional[ListNode]) -> List[int]:
        """Read node values from head to None back into a Python list for the judge."""
        result: List[int] = []
        node = head
        while node is not None:
            result.append(node.val)
            node = node.next
        return result
    
    
    def remove_target_values(values: List[int], target: int) -> List[int]:
        # Build the linked list, perform the in-place pointer removal, and serialize.
        head = build_linked_list(values)
        new_head = remove_elements(head, target)
        return linked_list_to_values(new_head)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a freight train where each car carries only a forward coupling to the car behind it (singly linked list: a chain of nodes in which every node stores a value plus one next reference to the following node). Uncoupling an unwanted car in place (rewiring existing references in constant extra memory rather than assembling a brand-new train) requires standing on the car ahead of it (prev) and hooking prev.next straight to current.next. Placing one temporary helper car at the very front (dummy, a sentinel node—a placeholder node positioned before head so even the original front node has a predecessor) lets a single loop handle removing the first car, interior clusters, the final car, or the entire train.

Filtering surviving numbers into newly allocated nodes takes O(n) extra memory and breaks the in-place constraint. Conversely, unlinking nodes in place without a sentinel forces separate special-case logic for stripping matching head nodes, where null-pointer bugs easily slip in when every node matches.

Walk through [8, 3, 8, 8, 2] with target = 8:

  1. Link dummy -> 8 -> 3 -> 8 -> 8 -> 2 -> None and set prev = dummy.
  2. prev.next is the leading 8: set dummy.next = 3 (bypassing 8) and keep prev on dummy.
  3. Now prev.next is 3 (keep): advance prev onto 3.
  4. prev.next is the first middle 8: set 3.next = second 8 while keeping prev on 3. On the next pass prev.next is the second 8, so set 3.next = 2 and still keep prev on 3.
  5. prev.next is 2 (keep): advance prev onto 2. Now prev.next is None, so return dummy.next (3 -> 2).

Complexity

  • Time: O(n) for an n-node list. Each pass of while prev.next is not None either unlinks one node permanently or moves prev forward by one node, so remove_elements runs exactly n iterations doing O(1) pointer updates per step. (Constructing and reading the list in the test adapter also take one O(n) pass each.)
  • Space: O(1) auxiliary space inside remove_elements, which allocates only one dummy sentinel node and two pointer variables (prev, current) regardless of n. (remove_target_values uses O(n) memory solely to translate the judge's List[int] input and output.)

Edge cases

  • Empty list (head is None / []): dummy.next begins as None, the loop performs zero iterations, and dummy.next returns None ([]).
  • All nodes match ([4, 4, 4, 4], target = 4): prev stays on dummy across all four unlinks until dummy.next becomes None, returning [].
  • Leading run of matches ([5, 5, 5, 1, 2], target = 5): dummy.next steps past all three 5s before prev ever advances onto 1.
  • Back-to-back interior matches ([1, 4, 4, 4, 2], target = 4): Holding prev stationary whenever a node is unlinked ensures every consecutive 4 is tested and deleted.
  • Trailing matches ([8, 3, 8, 5, 2, 8], target = 8): Unlinking the final 8 sets 2.next = None, cleanly terminating the chain.
  • Target absent ([10, -2, 7], target = 5): prev walks to the end without modifying any next pointer and returns the original head.
  • Long chains (10,000+ nodes): Iterative pointer traversal uses O(1) stack space and never hits Python's recursion depth cap.

Common mistakes

  • Advancing prev = prev.next immediately after unlinking: On 3 -> 8 -> 8 -> 2 with target = 8, unlinking the first 8 points 3.next at the second 8; stepping prev forward lands prev on that second 8 and skips deleting it!
  • Returning head rather than dummy.next: Whenever the original first node equaled target (as in [8, 3, 8, 5, 2, 8]), head still references that unlinked node instead of 3.
  • Using if instead of while when stripping front nodes without a sentinel: if head and head.val == target: head = head.next removes only the first matching head and fails on [4, 4, 4, 4].
  • Allocating fresh nodes for surviving elements: Violates the in-place pointer-modification requirement and costs O(n) extra node allocations.
  • Recursing on long lists in Python: head.next = remove_elements(head.next, target) pushes one frame per node onto the call stack (memory tracking active function invocations) and raises RecursionError around 1,000 nodes.

Alternative approaches

  • Two-loop iterative deletion without a sentinel (O(n) time, O(1) space): First strip leading matches via while head is not None and head.val == target: head = head.next; return None if head is None; otherwise run the prev loop starting at prev = head. Same complexity, slightly more branches to get right.
  • Pointer-to-pointer walk in C/C++ (O(n) time, O(1) space): Keep ListNode** indirect = &head; addressing whichever pointer (head or a node's next field) points to the current node. Assigning *indirect = (*indirect)->next unlinks head and interior nodes uniformly without even a stack sentinel.

Follow-up questions

  • How would you implement in-place deletion without creating a dummy sentinel node? First advance head past any matching prefix using while head is not None and head.val == target: head = head.next. Once that loop finishes, either head is None (return None right away) or head.val != target is guaranteed, allowing you to set prev = head and run while prev.next is not None over the rest of the chain before returning head.
  • Why do interviewers generally prefer an iterative pointer walk over recursion for this task? A recursive solution (head.next = remove_elements(head.next, target) followed by returning head.next when head.val == target) consumes O(n) call-stack frames instead of O(1) auxiliary memory. On a 10,000-node list, recursion triggers RecursionError in Python and risks stack overflow in C or C++.
  • What memory-management bug must you avoid if you port this code to C or C++? Unlike Python's garbage collector, C and C++ do not automatically reclaim unlinked heap nodes, so merely writing prev->next = prev->next->next creates a memory leak (allocated heap memory with no surviving pointer to free it). Conversely, freeing a node before reading its next pointer causes a use-after-free bug; always stash ListNode* victim = prev->next;, rewire prev->next = victim->next;, and only then call delete victim; (or free(victim);).

Follow-up questions

Similar questions

More Arista interview questions

All 5 Arista questions →