Merge Nodes in Between Zeros

Medium

Topics
Linked ListSimulation

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

before03104520null
after411null
separator zero
Each stretch between two zeros collapses into a single node holding its sum, and the zeros disappear.
Linked list values from head to tail.
Input:  head = [0,3,1,0,4,5,2,0]
Output: [4,11]

Example 2

before01030220null
after134null
separator zero
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

  1. Create a dummy node so the first append needs no special case.
  2. Walk from head.next, adding each non-zero value to a running total.
  3. On reaching a zero, append a node holding the total and reset the total to 0.
  4. 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 -> 11

Complexity

  • 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 head rather than head.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.next
SensAI
Beta
Tap the mic to stop voice mode