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 andO(1)extra space (excluding theO(n)conversion from and toList[int]in the test wrapper).
Step-by-step walkthrough
Understand the problem and the judge adapter
Starting from the front node
headof a singly linked list (a linear chain where each node holds an integervaland a forward referencenext), we need to unlink every node storingtargetin place—rewiring existingnextpointers withO(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:build_linked_list(values)builds aListNodechain from the input numbers,remove_elements(head, target)executes the genuineO(1)-space in-place pointer deletion, andlinked_list_to_values(new_head)collects the surviving node values back into a Python list.
Why deleting the head node is tricky without help
Unlinking an interior node
currentfrom a singly linked list requires standing on the node right before it (prev) so you can redirectprev.nexttocurrent.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 precedeshead! Without extra help, you would have to write a dedicatedwhileloop at the start just to peel off matching front nodes (such as[4, 4, 4, 4]withtarget = 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.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
headwithdummy.next = head:[dummy] -> [4] -> [4] -> [9] -> None ^ ^ prev head (now has a predecessor just like every interior node!)With
dummyin front, every real node—including the originalhead—is reached viaprev.nextfrom a predecessor nodeprev! Once the traversal ends,dummy.nextautomatically points to the new front node (orNonewhen every node matchedtarget). Because our loop only inspectsprev.next,dummy.val(0) is never tested againsttarget.Unlink matching nodes without skipping consecutive matches
Initialize
prev = dummyand inspectcurrent = prev.nextwhileprev.next is not None:- When
current.val == target: bypasscurrentviaprev.next = current.next. Crucially, keepprevwhere it is! Becausecurrent.nextjust moved intoprev.next, we have not checked its value yet—it could equaltargetas well! - When
current.val != target:currentsurvives, so stepprevforward ontocurrent.
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- When
Trace Example 1 and Example 2, and wire up the judge helpers
Let's walk
dummyandprevacross 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)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:
- Link
dummy -> 8 -> 3 -> 8 -> 8 -> 2 -> Noneand setprev = dummy. prev.nextis the leading8: setdummy.next = 3(bypassing8) and keepprevondummy.- Now
prev.nextis3(keep): advanceprevonto3. prev.nextis the first middle8: set3.next = second 8while keepingprevon3. On the next passprev.nextis the second8, so set3.next = 2and still keepprevon3.prev.nextis2(keep): advanceprevonto2. Nowprev.nextisNone, so returndummy.next(3 -> 2).
Complexity
- Time:
O(n)for ann-node list. Each pass ofwhile prev.next is not Noneeither unlinks one node permanently or movesprevforward by one node, soremove_elementsruns exactlyniterations doingO(1)pointer updates per step. (Constructing and reading the list in the test adapter also take oneO(n)pass each.) - Space:
O(1)auxiliary space insideremove_elements, which allocates only onedummysentinel node and two pointer variables (prev,current) regardless ofn. (remove_target_valuesusesO(n)memory solely to translate the judge'sList[int]input and output.)
Edge cases
- Empty list (
head is None/[]):dummy.nextbegins asNone, the loop performs zero iterations, anddummy.nextreturnsNone([]). - All nodes match (
[4, 4, 4, 4],target = 4):prevstays ondummyacross all four unlinks untildummy.nextbecomesNone, returning[]. - Leading run of matches (
[5, 5, 5, 1, 2],target = 5):dummy.nextsteps past all three5s beforeprevever advances onto1. - Back-to-back interior matches (
[1, 4, 4, 4, 2],target = 4): Holdingprevstationary whenever a node is unlinked ensures every consecutive4is tested and deleted. - Trailing matches (
[8, 3, 8, 5, 2, 8],target = 8): Unlinking the final8sets2.next = None, cleanly terminating the chain. - Target absent (
[10, -2, 7],target = 5):prevwalks to the end without modifying anynextpointer and returns the originalhead. - Long chains (
10,000+nodes): Iterative pointer traversal usesO(1)stack space and never hits Python's recursion depth cap.
Common mistakes
- Advancing
prev = prev.nextimmediately after unlinking: On3 -> 8 -> 8 -> 2withtarget = 8, unlinking the first8points3.nextat the second8; steppingprevforward landsprevon that second8and skips deleting it! - Returning
headrather thandummy.next: Whenever the original first node equaledtarget(as in[8, 3, 8, 5, 2, 8]),headstill references that unlinked node instead of3. - Using
ifinstead ofwhilewhen stripping front nodes without a sentinel:if head and head.val == target: head = head.nextremoves 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 raisesRecursionErroraround 1,000 nodes.
Alternative approaches
- Two-loop iterative deletion without a sentinel (
O(n)time,O(1)space): First strip leading matches viawhile head is not None and head.val == target: head = head.next; returnNoneifhead is None; otherwise run theprevloop starting atprev = head. Same complexity, slightly more branches to get right. - Pointer-to-pointer walk in C/C++ (
O(n)time,O(1)space): KeepListNode** indirect = &head;addressing whichever pointer (heador a node'snextfield) points to the current node. Assigning*indirect = (*indirect)->nextunlinks 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
headpast any matching prefix usingwhile head is not None and head.val == target: head = head.next. Once that loop finishes, eitherheadisNone(returnNoneright away) orhead.val != targetis guaranteed, allowing you to setprev = headand runwhile prev.next is not Noneover the rest of the chain before returninghead. - 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 returninghead.nextwhenhead.val == target) consumesO(n)call-stack frames instead ofO(1)auxiliary memory. On a 10,000-node list, recursion triggersRecursionErrorin 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->nextcreates a memory leak (allocated heap memory with no surviving pointer to free it). Conversely, freeing a node before reading itsnextpointer causes a use-after-free bug; always stashListNode* victim = prev->next;, rewireprev->next = victim->next;, and only then calldelete victim;(orfree(victim);).
Follow-up questions
- How would you implement in-place deletion without creating a dummy sentinel node?
- Why do interviewers generally prefer an iterative pointer walk over recursion for this task?
- What memory-management bug must you avoid if you port this code to C or C++?
Similar questions
- Missing Integer in a Sorted Step-One Sequence
- Palindrome Verification and Skipped-Number Search
- Pointer Indirection, Format Specifiers, and Process Segments in C
- Raw-Storage Generic C++ Stack and Lifetime Semantics
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger