Ctrl K

Sums Between Zeros

Medium
You are given a singly linked list head of non-negative integers. The list starts and ends with a zero, and the zeros split it into blocks: between any two neighbouring zeros there is at least one non-zero value. Replace every block with a single node holding the sum of that block, and drop the zeros. Return the head of the new list: the block sums in their original order.
Example 1
head=list_node([0, 2, 7, 0, 5, 0]) → [9, 5]

Between the first two zeros 2 + 7 = 9, between the second and third there is just 5. Answer: [9, 5].

Example 2
head=list_node([0, 4, 4, 4, 4, 0]) → [16]

There is a single block with sum 16.

Example 3
head=list_node([0, 1, 0, 30, 0, 6, 1, 0]) → [1, 30, 7]
Constraints
  • The list has between 3 and 2·10⁵ nodes
  • 0 ≤ Node.val ≤ 1000
  • The first and last nodes are 0
  • No two zeros are adjacent
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPour a List Into a Spiral MediumAdding Digit Lists MediumDrop the K-th Node From the Tail MediumTrade Places in Twos MediumMultiplying Digit Strings Medium
loading Python…
Input
head=list_node([0, 2, 7, 0, 5, 0])
Expected
[9, 5]

Run checks the first 3 tests in your browser. Submit checks all 91 tests on the server, hidden ones included.