Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of ListNode objects.)
Example 1:
Input: head = [1,2,-3,3,1] Output: [3,1] Note: The answer [1,2,1] would also be accepted.
Example 2:
Input: head = [1,2,3,-3,4] Output: [1,2,4]
Example 3:
Input: head = [1,2,3,-3,-2] Output: [1]
Constraints:
1 and 1000 nodes.-1000 <= node.val <= 1000.Problem summary: Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of ListNode objects.)
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Linked List
[1,2,-3,3,1]
[1,2,3,-3,4]
[1,2,3,-3,-2]
delete-n-nodes-after-m-nodes-of-a-linked-list)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1171: Remove Zero Sum Consecutive Nodes from Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeZeroSumSublists(ListNode head) {
ListNode dummy = new ListNode(0, head);
Map<Integer, ListNode> last = new HashMap<>();
int s = 0;
ListNode cur = dummy;
while (cur != null) {
s += cur.val;
last.put(s, cur);
cur = cur.next;
}
s = 0;
cur = dummy;
while (cur != null) {
s += cur.val;
cur.next = last.get(s).next;
cur = cur.next;
}
return dummy.next;
}
}
// Accepted solution for LeetCode #1171: Remove Zero Sum Consecutive Nodes from Linked List
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeZeroSumSublists(head *ListNode) *ListNode {
dummy := &ListNode{0, head}
last := map[int]*ListNode{}
cur := dummy
s := 0
for cur != nil {
s += cur.Val
last[s] = cur
cur = cur.Next
}
s = 0
cur = dummy
for cur != nil {
s += cur.Val
cur.Next = last[s].Next
cur = cur.Next
}
return dummy.Next
}
# Accepted solution for LeetCode #1171: Remove Zero Sum Consecutive Nodes from Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(next=head)
last = {}
s, cur = 0, dummy
while cur:
s += cur.val
last[s] = cur
cur = cur.next
s, cur = 0, dummy
while cur:
s += cur.val
cur.next = last[s].next
cur = cur.next
return dummy.next
// Accepted solution for LeetCode #1171: Remove Zero Sum Consecutive Nodes from Linked List
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn remove_zero_sum_sublists(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let dummy = Some(Box::new(ListNode { val: 0, next: head }));
let mut last = std::collections::HashMap::new();
let mut s = 0;
let mut p = dummy.as_ref();
while let Some(node) = p {
s += node.val;
last.insert(s, node);
p = node.next.as_ref();
}
let mut dummy = Some(Box::new(ListNode::new(0)));
let mut q = dummy.as_mut();
s = 0;
while let Some(cur) = q {
s += cur.val;
if let Some(node) = last.get(&s) {
cur.next = node.next.clone();
}
q = cur.next.as_mut();
}
dummy.unwrap().next
}
}
// Accepted solution for LeetCode #1171: Remove Zero Sum Consecutive Nodes from Linked List
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function removeZeroSumSublists(head: ListNode | null): ListNode | null {
const dummy = new ListNode(0, head);
const last = new Map<number, ListNode>();
let s = 0;
for (let cur = dummy; cur; cur = cur.next) {
s += cur.val;
last.set(s, cur);
}
s = 0;
for (let cur = dummy; cur; cur = cur.next) {
s += cur.val;
cur.next = last.get(s)!.next;
}
return dummy.next;
}
Use this to step through a reusable interview workflow for this problem.
Copy all n nodes into an array (O(n) time and space), then use array indexing for random access. Operations like reversal or middle-finding become trivial with indices, but the O(n) extra space defeats the purpose of using a linked list.
Most linked list operations traverse the list once (O(n)) and re-wire pointers in-place (O(1) extra space). The brute force often copies nodes to an array to enable random access, costing O(n) space. In-place pointer manipulation eliminates that.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Pointer updates overwrite references before they are saved.
Usually fails on: List becomes disconnected mid-operation.
Fix: Store next pointers first and use a dummy head for safer joins.