Merge Nodes in Between Zeros (LeetCode 2181): Solution and Explanation

Medium
Linked List
Simulation

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

  1. Set tail = head, node = head.next and total = 0.
  2. While node is not null, if node.val is non-zero, add it to total.
  3. If node.val is 0, a segment just ended: move tail to tail.next, set tail.val = total, and reset total = 0.
  4. Advance node to node.next.
  5. After the loop, set tail.next = None to drop the unused nodes.
  6. Return head.next.

Step-by-step example

head = [0,3,1,0,4,5,2,0]
  1. tail is at index 0, node starts at index 1.
  2. Read 3 and 1, so total = 4.
  3. The 0 at index 3 ends the segment. tail moves to index 1 and its value becomes 4.
  4. Read 4, 5 and 2, so total = 11.
  5. The final 0 ends the segment. tail moves to index 2 and its value becomes 11.
  6. 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.next
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is read exactly once, and each sum is written once.

Space

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 head instead of head.next, which keeps the leading 0 in the output.
  • Forgetting tail.next = None, so the original nodes after the last sum stay attached.
  • Resetting total before 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.