Merge Nodes in Between Zeros

You are given the head of a linked list, which contains a series of integers separated by 0s. The beginning and end of the list both have Node.val == 0. For every two consecutive 0s, merge all the nodes lying between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0s. Return the head of the modified linked list.

30:00

Merge Nodes in Between Zeros
medium
Free written solution
Topics
Companies

You are given the head of a linked list, which contains a series of integers separated by 0s. The beginning and end of the list both have Node.val == 0. For every two consecutive 0s, merge all the nodes lying between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0s. Return the head of the modified linked list.

Example 1:
Input: {"head":[0,3,1,0,4,5,2,0]}
Output: [4,11]
Constraints:
  • The number of nodes in the list is in the range [3,2×105][3, 2 \times 10^5].

  • 0≤Node.val≤10000 \leq \text{Node.val} \leq 1000

  • There are no two consecutive nodes with Node.val == 0.

  • The beginning and end of the linked list have Node.val == 0.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[0,3,1,0,4,5,2,0]}

Two pointers walk the same list. node reads ahead and adds values into total; tail lags behind and, at each 0, steps forward and overwrites that node with the finished sum. No new nodes are created.

total0
sums written0

The list in memory (dashed circles are the 0 separators)

0

tail

→
3

node

→
1

→
0

→
4

→
5

→
2

→
0

head.next onward (the merged list)

no segment closed yet

■ node (reads)■ tail (writes sums)✂ cut after the last sum
Variables
VariableValue
tail0
node1
total0
DepthFunction Call
Stack empty
0/9