Merge Nodes in Between Zeros

Medium Topics Company Tags

The linked list begins and ends with zero, and its other zero-valued nodes separate nonempty groups of positive values. Replace each group between successive zeros with one node containing the sum of that group. Remove all zero-valued separator nodes and preserve the order of the groups. Return the head of the resulting list. Arrays in examples and test inputs show node values from head to tail.

Example 1:

Merge Nodes in Between Zeros, example 1: illustration of the example

Input: head = [0,2,5,0,4,0]

Output: [7,4]

Explanation: The first group sums to 2 + 5 = 7, and the second contains only 4. Remove the zeros to obtain 7 -> 4.

Example 2:

Merge Nodes in Between Zeros, example 2: illustration of the example

Input: head = [0,7,0]

Output: [7]

Explanation: There is one group, containing 7. Its sum is 7, so the resulting list has one node.

Example 3:

Merge Nodes in Between Zeros, example 3: illustration of the example

Input: head = [0,1,2,3,0,5,5,0]

Output: [6,10]

Explanation: The groups sum to 1 + 2 + 3 = 6 and 5 + 5 = 10. Their order is preserved in the resulting chain 6 -> 10.

Constraints:

  • The list contains between 3 and 200000 nodes.
  • 0 <= Node.val <= 1000
  • The first and last nodes have value 0.
  • No two adjacent nodes both have value 0.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.