Merge Nodes in Between Zeros - Problem

You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.

For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.

Return the head of the modified linked list.

Input & Output

Example 1 — Basic Case
$ Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
💡 Note: Between first and second zero: 3+1=4. Between second and third zero: 4+5+2=11. Result is [4,11].
Example 2 — Single Segment
$ Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
💡 Note: Three segments: [1] gives 1, [3] gives 3, [2,2] gives 4. Result is [1,3,4].
Example 3 — Larger Values
$ Input: head = [0,10,20,0,5,15,0]
Output: [30,20]
💡 Note: First segment: 10+20=30. Second segment: 5+15=20. Result is [30,20].

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 two consecutive nodes with Node.val == 0.

Visualization

Tap to expand
Merge Nodes in Between Zeros Single Pass In-Place Approach INPUT Linked List Structure: 0 3 1 0 4 5 2 0 Zero nodes (separators) Value nodes (to merge) Input Array: [0,3,1,0,4,5,2,0] Segment 1: 3+1=4 Segment 2: 4+5+2=11 ALGORITHM STEPS 1 Initialize Pointers Start after first 0 modify = head.next 2 Traverse & Sum Accumulate values until next 0 found 3 Store Sum Set modify.val = sum Move to next segment 4 Link & Repeat Skip zeros, link nodes Return head.next In-Place Modification: 0 3 1 0 4 5 2 0 4 11 FINAL RESULT Modified Linked List: 4 11 NULL First Segment: 3 + 1 = 4 Values between 1st and 2nd zero Second Segment: 4 + 5 + 2 = 11 Values between 2nd and 3rd zero Output Array: [4, 11] OK - Complete! Key Insight: Single pass in-place modification: Use two pointers - one to write merged sums, one to read values. Zeros act as delimiters. Sum all values between consecutive zeros, skip zeros in output. Time: O(n) | Space: O(1) - Modifies list in-place without extra storage TutorialsPoint - Merge Nodes in Between Zeros | Single Pass In-Place Approach
Asked in
Microsoft 45 Amazon 38 Facebook 32 Google 28
68.0K Views
Medium Frequency
~15 min Avg. Time
2.1K 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