Remove Zero Sum Consecutive Nodes from Linked List (LeetCode 1171): Solution and Explanation
Repeatedly delete runs of consecutive nodes whose values sum to 0 until none remain, and return the head of the final list.
Intuition
A run of nodes sums to 0 exactly when the running total before the run equals the running total at its end. So zero-sum runs are pairs of positions with the same prefix sum.
A dummy node with value 0 in front gives the empty prefix a node of its own, so a run that starts at the head is caught like any other.
If a prefix sum appears several times, everything between its first and last appearance cancels out. Jumping from the first node with that prefix straight to the node after its last one removes all of it in one link.
Two passes do it: the first records, for each prefix sum, the last node that has it; the second walks from the dummy and sets node.next = last[prefix].next.
Approach: Prefix sums with a last-occurrence map
- Create dummy = ListNode(0, head).
- Pass 1: walk from dummy keeping a running prefix sum and store last[prefix] = node, so later nodes overwrite earlier ones.
- Pass 2: walk from dummy again with a fresh prefix sum. At each node set node.next = last[prefix].next, then move to node.next.
- Return dummy.next.
Step-by-step example
head = [3,4,1,-1,-4,2,6,-6]
- Prefix sums including the dummy: 0, 3, 7, 8, 7, 3, 5, 11, 5.
- Pass 1 leaves last[0] = dummy, last[3] = node -4, last[7] = node -1, last[8] = node 1, last[5] = node -6, last[11] = node 6.
- Pass 2 at dummy (prefix 0): next stays node 3.
- At node 3 (prefix 3): last[3] is node -4, so node 3 links to node 2, cutting [4,1,-1,-4].
- At node 2 (prefix 5): last[5] is node -6, so node 2 links to null, cutting [6,-6]. Result [3,2].
Code: Python, Java, C++
1class Solution:
2 def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
3 dummy = ListNode(0, head)
4 last = {}
5 prefix = 0
6 node = dummy
7 while node:
8 prefix += node.val
9 last[prefix] = node
10 node = node.next
11 prefix = 0
12 node = dummy
13 while node:
14 prefix += node.val
15 node.next = last[prefix].next
16 node = node.next
17 return dummy.next1class Solution {
2 public ListNode removeZeroSumSublists(ListNode head) {
3 ListNode dummy = new ListNode(0, head);
4 Map<Integer, ListNode> last = new HashMap<>();
5 int prefix = 0;
6 for (ListNode node = dummy; node != null; node = node.next) {
7 prefix += node.val;
8 last.put(prefix, node);
9 }
10 prefix = 0;
11 for (ListNode node = dummy; node != null; node = node.next) {
12 prefix += node.val;
13 node.next = last.get(prefix).next;
14 }
15 return dummy.next;
16 }
17}1class Solution {
2public:
3 ListNode* removeZeroSumSublists(ListNode* head) {
4 ListNode dummy(0);
5 dummy.next = head;
6 unordered_map<int, ListNode*> last;
7 int prefix = 0;
8 for (ListNode* node = &dummy; node != nullptr; node = node->next) {
9 prefix += node->val;
10 last[prefix] = node;
11 }
12 prefix = 0;
13 for (ListNode* node = &dummy; node != nullptr; node = node->next) {
14 prefix += node->val;
15 node->next = last[prefix]->next;
16 }
17 return dummy.next;
18 }
19};Time and space complexity
O(n)
Two linear passes with O(1) map operations.
O(n)
The map can hold one entry per distinct prefix sum.
Other approaches
Restart after each deletion (time O(n^2), space O(n))
Find any zero-sum run with a prefix map, cut it, and start over. Correct but can repeat the scan up to n times.
Check every start node (time O(n^2), space O(1))
From each node, sum forward and cut at the farthest point where the sum hits 0. No extra memory but quadratic.
Common mistakes
- Leaving out the dummy node, which misses runs that start at the head, such as [1,-1,2].
- Storing the first occurrence instead of the last. Jumping to the first one does not skip anything.
- Forgetting that a value of 0 is itself a zero-sum run of length one.
Frequently asked questions
Can there be more than one correct answer?
On LeetCode, yes. For [1,2,-3,3,1] you can delete [1,2,-3] or [-3,3], giving [3,1] or [1,2,1], and LeetCode accepts any valid final list. The tests here only use lists whose final list is the same whichever run you delete first.
Why does jumping to the last occurrence remove nested runs too?
Every node between the first and last position with the same prefix sum lies inside one zero-sum block, so all nested runs vanish with it.
Why does the second pass recompute the prefix sum?
Nodes it lands on keep the prefix sums they had in the original list, because the skipped nodes summed to 0. So recomputing along the new path gives the same keys used in pass 1.
What is the complexity?
O(n) time and O(n) space.