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
Understanding the Visualization
1
Input
Linked list with zeros separating segments
2
Process
Sum values between consecutive zeros
3
Output
New list with merged segment sums
Key Takeaway
🎯 Key Insight: Transform zero nodes into sum nodes while traversing, eliminating the need for extra space
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code