Merge Nodes in Between Zeros
Medium
Topics
You are given the head of a linked list that begins and ends with 0; between every pair of consecutive 0s there is at least one node. Merge each block of nodes between two zeros into a single node whose value is their sum, then return the resulting list (which no longer contains any 0).
Example 1
Input: head = [0,3,1,0,4,5,2,0] Output: [4,11]
Example 2
Input: head = [0,1,0,3,0,2,2,0] Output: [1,3,4]
Constraints
- 3 <= number of nodes <= 2*10^5
- 0 <= Node.val <= 1000
- The list starts and ends with 0.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The zeros are delimiters, not data. One pass accumulates values between them and emits a node each time a closing zero arrives. The guarantee that the list starts and ends with 0 means every block is properly terminated, so no flush is needed after the loop.
Start from head.next, not head — head is the leading delimiter and treating it as a block boundary would emit a spurious 0.
Approach
- Create a dummy node so the first append needs no special case.
- Walk from
head.next, adding each non-zero value to a running total. - On reaching a zero, append a node holding the total and reset the total to 0.
- Return
dummy.next.
Dry Run
input 0 -> 3 -> 1 -> 0 -> 4 -> 5 -> 2 -> 0 (walk starts after the leading 0)
node running sum emit
3 3 -
1 4 -
0 4 yes -> 4
4 4 -
5 9 -
2 11 -
0 11 yes -> 11
answer 4 -> 11Complexity
- Time — O(n): one pass, each node visited once.
- Space — O(1) auxiliary. The returned list is output, not working memory, so it is conventionally excluded. Worth being precise here, because the shown code does allocate one new node per block; the truly allocation-free variant reuses each block's first node as the holder for that block's sum and relinks around the rest. That is the natural follow-up question.
Common Pitfalls
- Starting the walk at
headrather thanhead.next, which treats the leading zero as a block terminator and emits a leading 0. - Emitting on the zero that opens a block instead of the one that closes it, which shifts every sum one block later and drops the last.
- Forgetting to reset the accumulator after an emit, so sums become cumulative across blocks.
- Leaving the output list unterminated. Building with a dummy head avoids this because fresh nodes have a null next, but a variant that relinks existing nodes must null the final one explicitly.
- Allocating a Python list of sums and rebuilding the list afterwards. It is the same complexity but gives up the single-pass, no-extra-structure property the problem is testing.
Full Solution — all languages
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeNodes(self, head):
dummy = ListNode(0)
tail = dummy
cur = head.next
total = 0
while cur:
if cur.val == 0:
tail.next = ListNode(total)
tail = tail.next
total = 0
else:
total += cur.val
cur = cur.next
return dummy.nextimport java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode mergeNodes(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
ListNode cur = head.next;
int total = 0;
while (cur != null) {
if (cur.val == 0) {
tail.next = new ListNode(total);
tail = tail.next;
total = 0;
} else total += cur.val;
cur = cur.next;
}
return dummy.next;
}
}#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(nullptr) {
}
};
class Solution {
public: ListNode* mergeNodes(ListNode* head) {
ListNode dummy(0);
ListNode* tail = &dummy;
ListNode* cur = head->next;
int total = 0;
while (cur) {
if (cur->val == 0) {
tail->next = new ListNode(total);
tail = tail->next;
total = 0;
} else total += cur->val;
cur = cur->next;
}
return dummy.next;
}
};/** Node shape: { val, next }. Build/return plain objects or use this ctor. */ function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
/**
* @param {ListNode} head
* @return {ListNode}
*/ var mergeNodes = function(head) {
const dummy = new ListNode(0);
let tail = dummy, cur = head.next, total = 0;
while (cur) {
if (cur.val === 0) {
tail.next = new ListNode(total);
tail = tail.next;
total = 0;
} else total += cur.val;
cur = cur.next;
}
return dummy.next;
};