Merge Nodes in Between Zeros - Problem

Imagine you have a linked list that acts like a series of compartments separated by walls (zeros). Your task is to merge all items within each compartment and remove the walls!

Given the head of a linked list containing integers, where 0s act as separators, you need to:

  • Sum all nodes between each pair of consecutive zeros
  • Replace each group with a single node containing the sum
  • Remove all zeros from the final result

The input list is guaranteed to start and end with 0, ensuring clean boundaries for your merging operation.

Goal: Return the head of the modified linked list with merged sums and no zeros.

Input & Output

example_1.py โ€” Basic Case
$ Input: head = [0,3,1,0,4,5,2,0]
โ€บ Output: [4,11]
๐Ÿ’ก Note: First segment between zeros: 3+1=4. Second segment: 4+5+2=11. Remove all zeros and return merged list.
example_2.py โ€” Single Elements
$ Input: head = [0,1,0,3,0,2,2,0]
โ€บ Output: [1,3,4]
๐Ÿ’ก Note: Three segments: first has 1, second has 3, third has 2+2=4. Each segment creates one merged node.
example_3.py โ€” Large Numbers
$ Input: head = [0,10,20,0,5,15,25,0]
โ€บ Output: [30,45]
๐Ÿ’ก Note: First segment: 10+20=30. Second segment: 5+15+25=45. Shows the algorithm works with larger values.

Constraints

  • The number of nodes in the list is in the range [3, 2 ร— 105]
  • 0 โ‰ค Node.val โ‰ค 1000
  • The beginning and end of the linked list have Node.val == 0
  • There are no consecutive zeros in the input except at the boundaries

Visualization

Tap to expand
Warehouse Consolidation Process0Wall310Wall4520Wall3+1=44+5+2=114Consolidated11ConsolidatedProcess:1. Skip walls (zeros)2. Sum items in section3. Create consolidated box4. Repeat for all sectionsResult: Clean warehouse with consolidated boxes only!
Understanding the Visualization
1
Start After First Wall
Begin processing from the first item after the initial wall (zero)
2
Accumulate Section Items
Keep a running total of all items in the current section
3
Hit Wall - Consolidate
When we hit a wall (zero), create a consolidated box with the total
4
Reset and Continue
Reset our counter and continue to the next section
5
Final Result
End with a clean warehouse containing only consolidated boxes
Key Takeaway
๐ŸŽฏ Key Insight: Single pass with running sum eliminates the need for multiple traversals, making the solution both time and space optimal
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22
89.3K Views
Medium Frequency
~12 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen