Merge Nodes in Between Zeros (LeetCode 2181): Solution and Explanation
A linked list starts and ends with 0 and has 0s separating groups of positive values. Replace each group with one node holding its sum, drop all the 0s, and return the new head.
Intuition
Each segment between two 0s collapses into a single number, so the job is a running sum that is emitted and reset every time a 0 shows up. One walk of the list is enough to compute all the sums.
The interesting part is where to put them without allocating new nodes. Every segment has at least one value, so by the time the k-th sum is ready, the reader has already passed at least 2k nodes. A second pointer that moves one node per finished sum can never catch up with the reader.
That second pointer, tail, starts at the leading 0. At each 0 it steps forward one node and overwrites that node's value with the sum. The value it destroys was already read and added, so nothing is lost.
When the reader falls off the end, the sums sit in the nodes right after the head. Cutting tail.next drops the leftovers, and head.next is the answer.
Approach: Read pointer and lagging write pointer
- Set
tail = head,node = head.nextandtotal = 0. - While
nodeis not null, ifnode.valis non-zero, add it tototal. - If
node.valis 0, a segment just ended: movetailtotail.next, settail.val = total, and resettotal = 0. - Advance
nodetonode.next. - After the loop, set
tail.next = Noneto drop the unused nodes. - Return
head.next.
Step-by-step example
head = [0,3,1,0,4,5,2,0]
- tail is at index 0, node starts at index 1.
- Read 3 and 1, so total = 4.
- The 0 at index 3 ends the segment. tail moves to index 1 and its value becomes 4.
- Read 4, 5 and 2, so total = 11.
- The final 0 ends the segment. tail moves to index 2 and its value becomes 11.
- Cut after index 2 and return head.next = [4, 11].
Code: Python, Java, C++
1class Solution:
2 def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
3 tail = head
4 node = head.next
5 total = 0
6 while node:
7 if node.val != 0:
8 total += node.val
9 else:
10 tail = tail.next
11 tail.val = total
12 total = 0
13 node = node.next
14 tail.next = None
15 return head.next1class Solution {
2 public ListNode mergeNodes(ListNode head) {
3 ListNode tail = head;
4 ListNode node = head.next;
5 int total = 0;
6 while (node != null) {
7 if (node.val != 0) {
8 total += node.val;
9 } else {
10 tail = tail.next;
11 tail.val = total;
12 total = 0;
13 }
14 node = node.next;
15 }
16 tail.next = null;
17 return head.next;
18 }
19}1class Solution {
2public:
3 ListNode* mergeNodes(ListNode* head) {
4 ListNode* tail = head;
5 ListNode* node = head->next;
6 int total = 0;
7 while (node) {
8 if (node->val != 0) {
9 total += node->val;
10 } else {
11 tail = tail->next;
12 tail->val = total;
13 total = 0;
14 }
15 node = node->next;
16 }
17 tail->next = nullptr;
18 return head->next;
19 }
20};Time and space complexity
O(n)
Each node is read exactly once, and each sum is written once.
O(1)
The sums reuse existing nodes, so only two pointers and the running total are kept.
Other approaches
Build a new list (time O(n), space O(k))
Append a new node with each finished sum to a dummy-headed result list. It is the most direct version and leaves the input values unchanged, at the cost of O(k) new nodes for k segments.
Reuse the zero nodes (time O(n), space O(1))
Store each segment's sum in the 0 that opens it and link that 0 straight to the next 0. This also works in place, but needs more pointer surgery than overwriting values.
Common mistakes
- Returning
headinstead ofhead.next, which keeps the leading 0 in the output. - Forgetting
tail.next = None, so the original nodes after the last sum stay attached. - Resetting
totalbefore writing it, which stores 0 instead of the segment sum. - Emitting a sum for the leading 0. The loop starts at
head.next, so the first 0 is never treated as the end of a segment.
Frequently asked questions
Why is it safe to overwrite node values while still reading?
Every segment holds at least one value, so the write pointer moves at most half as fast as the reader. It only ever overwrites nodes that were already read.
Can a segment be empty?
No. The constraints say no two 0s are adjacent, so every pair of consecutive 0s has at least one value between them.
Does overflow matter?
Not here. At most 2 * 10^5 nodes with values up to 1000 gives sums below 2 * 10^8, which fits in a 32-bit integer.
What is the time complexity of Merge Nodes in Between Zeros?
O(n) time with one pass and O(1) extra space when the sums are written in place.