medium Merge Nodes in Between Zeros
Problem Statement
You are given a head of the linked list where each node contains an integer. This list has segments separated by nodes with the value 0. The list starts and ends with a node containing 0.
For every pair of consecutive nodes with the value 0, merge all the nodes between them into a single node whose value is the sum of these nodes. The modified linked list should not include any 0 nodes.
Return the head of the updated linked list.
Examples
Example 1:
- Input: head =
[0, 2, 3, 0, 4, 5, 0, 3, 0, 4, 0] - Expected Output:
[5, 9, 3, 4] - Justification: The segments between
0s are[2, 3],[4, 5],[3], and[4]. Summing these segments gives5,9,3, and4, respectively.
Example 2:
- Input: head =
[0, 1, 1, 1, 0, 2, 2, 0] - Expected Output:
[3, 4] - Justification: The segments between
0s are[1, 1, 1]and[2, 2]. Summing these segments gives3and4, respectively.
Example 3:
- Input: head =
[0, 5, 0, 10, 15, 0] - Expected Output:
[5, 25] - Justification: The segments between
0s are[5]and[10, 15]. Summing these segments gives5and25, respectively.
Constraints:
- The number of nodes in the list is in the range [3, 2 * 105].
- 0 <= Node.val <= 1000
- There are no two consecutive nodes with Node.val == 0.
- The beginning and end of the linked list have Node.val == 0.
Try it yourself
Try solving this question here:
✅ Solution Merge Nodes in Between Zeros
Problem Statement
You are given a head of the linked list where each node contains an integer. This list has segments separated by nodes with the value 0. The list starts and ends with a node containing 0.
For every pair of consecutive nodes with the value 0, merge all the nodes between them into a single node whose value is the sum of these nodes. The modified linked list should not include any 0 nodes.
Return the head of the updated linked list.
Examples
Example 1:
- Input: head =
[0, 2, 3, 0, 4, 5, 0, 3, 0, 4, 0] - Expected Output:
[5, 9, 3, 4] - Justification: The segments between
0s are[2, 3],[4, 5],[3], and[4]. Summing these segments gives5,9,3, and4, respectively.
Example 2:
- Input: head =
[0, 1, 1, 1, 0, 2, 2, 0] - Expected Output:
[3, 4] - Justification: The segments between
0s are[1, 1, 1]and[2, 2]. Summing these segments gives3and4, respectively.
Example 3:
- Input: head =
[0, 5, 0, 10, 15, 0] - Expected Output:
[5, 25] - Justification: The segments between
0s are[5]and[10, 15]. Summing these segments gives5and25, respectively.
Constraints:
- The number of nodes in the list is in the range [3, 2 * 105].
- 0 <= Node.val <= 1000
- There are no two consecutive nodes with Node.val == 0.
- The beginning and end of the linked list have Node.val == 0.
Solution
To solve this problem, you start by creating a helper or dummy node that will assist in managing the merging process. You then traverse the linked list, summing the values of nodes between two zeroes. When a zero is encountered, this sum is assigned to the current node. This approach is efficient because it ensures a single pass through the linked list, maintaining simplicity while managing the summing process within the nodes.
Step-by-step Algorithm
-
Initialize Helper Nodes:
- Create a
helperNodeinitialized tohead.nextto assist in merging nodes. This will be the node where we store the accumulated sums. - Set
sumNodetohelperNodeto start the accumulation process. This node will traverse the list and accumulate the sums between zeros.
- Create a
-
Loop Through the List:
- While
sumNodeis not null:-
This loop ensures we process all nodes in the list until we reach the end.
-
-
Accumulate Sum Between Zeros:
- Initialize
accumulatedSumto 0:- This variable will keep track of the sum of node values between two zeros.
- While
sumNode.valis not 0:- This inner loop continues until we find a zero, indicating the end of the current segment.
- Accumulate the value of
sumNodeintoaccumulatedSum:- Add the current node's value to
accumulatedSumto keep a running total of the segment's values.
- Add the current node's value to
- Move
sumNodeto the next node:- Advance to the next node in the list to continue accumulation.
- Initialize
-
Update the Helper Node with Accumulated Sum:
- Assign
accumulatedSumtohelperNode.val:- Store the accumulated sum in the current
helperNode. This step replaces the value of the helper node with the sum of the segment, effectively merging the nodes.
- Store the accumulated sum in the current
- Assign
-
Move to the Next Segment:
- Move
sumNodeto the next node after the zero:- Skip the zero node and move to the start of the next segment.
- Update
helperNode.nexttosumNode:- Link the current helper node to the start of the next segment.
- Move
helperNodetohelperNode.next:- Advance
helperNodeto the next node where the next accumulated sum will be stored.
- Advance
- Move
- While
-
Return the Result:
- Return
head.nextwhich points to the merged list starting from the first accumulated sum. This skips the initial zero node in the original list.
- Return
Algorithm Walkthrough
Using the input [0, 2, 3, 0, 4, 5, 0, 3, 0, 4, 0]:
-
Initialization:
helperNodepoints to the node with value2(the first non-zero node).sumNodealso points to the node with value2.
-
First Segment:
accumulatedSumis initialized to0.- Traverse nodes
2and3:accumulatedSumbecomes2after the first node.accumulatedSumbecomes5after the second node.
sumNodereaches the node with value0.- Set
helperNode.valto5. - Move
sumNodeto the next node (4). - Set
helperNode.nexttosumNode. - Move
helperNodeto the node with value4.
-
Second Segment:
accumulatedSumis reset to0.- Traverse nodes
4and5:accumulatedSumbecomes4after the first node.accumulatedSumbecomes9after the second node.
sumNodereaches the node with value0.- Set
helperNode.valto9. - Move
sumNodeto the next node (3). - Set
helperNode.nexttosumNode. - Move
helperNodeto the node with value3.
-
Third Segment:
accumulatedSumis reset to0.- Traverse the node
3:accumulatedSumbecomes3.
sumNodereaches the node with value0.- Set
helperNode.valto3. - Move
sumNodeto the next node (4). - Set
helperNode.nexttosumNode. - Move
helperNodeto the node with value4.
-
Fourth Segment:
accumulatedSumis reset to0.- Traverse the node
4:accumulatedSumbecomes4.
sumNodereaches the node with value0.- Set
helperNode.valto4. - Move
sumNodeto the next node (null). - Set
helperNode.nexttonull.
-
End of List:
sumNodeisnull, so the traversal ends.
-
Return the Result:
- Return the node following the initial
0node. - The resulting linked list is
[5, 9, 3, 4].
- Return the node following the initial
Code
// class ListNode {
// int val;
// ListNode next;
// ListNode(int val) { this.val = val; }
// }
public class Solution {
public ListNode mergeNodes(ListNode head) {
// Create a placeholder node to assist in merging
ListNode helperNode = head.next;
ListNode sumNode = helperNode;
while (sumNode != null) {
int accumulatedSum = 0;
// Accumulate sum of nodes between zeros
while (sumNode.val != 0) {
accumulatedSum += sumNode.val;
sumNode = sumNode.next;
}
// Assign the accumulated sum to the current node's value
helperNode.val = accumulatedSum;
// Move sumNode to the first non-zero value of the next segment
sumNode = sumNode.next;
// Move helperNode also to this node
helperNode.next = sumNode;
helperNode = helperNode.next;
}
return head.next;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test Example 1
ListNode head1 = new ListNode(0);
head1.next = new ListNode(2);
head1.next.next = new ListNode(3);
head1.next.next.next = new ListNode(0);
head1.next.next.next.next = new ListNode(4);
head1.next.next.next.next.next = new ListNode(5);
head1.next.next.next.next.next.next = new ListNode(0);
head1.next.next.next.next.next.next.next = new ListNode(3);
head1.next.next.next.next.next.next.next.next = new ListNode(0);
head1.next.next.next.next.next.next.next.next.next = new ListNode(4);
head1.next.next.next.next.next.next.next.next.next.next = new ListNode(0);
ListNode result1 = sol.mergeNodes(head1);
while (result1 != null) {
System.out.print(result1.val + " ");
result1 = result1.next;
}
System.out.println(" ");
// Test Example 2
ListNode head2 = new ListNode(0);
head2.next = new ListNode(1);
head2.next.next = new ListNode(1);
head2.next.next.next = new ListNode(1);
head2.next.next.next.next = new ListNode(0);
head2.next.next.next.next.next = new ListNode(2);
head2.next.next.next.next.next.next = new ListNode(2);
head2.next.next.next.next.next.next.next = new ListNode(0);
ListNode result2 = sol.mergeNodes(head2);
while (result2 != null) {
System.out.print(result2.val + " ");
result2 = result2.next;
}
System.out.println(" ");
// Test Example 3
ListNode head3 = new ListNode(0);
head3.next = new ListNode(5);
head3.next.next = new ListNode(0);
head3.next.next.next = new ListNode(10);
head3.next.next.next.next = new ListNode(15);
head3.next.next.next.next.next = new ListNode(0);
ListNode result3 = sol.mergeNodes(head3);
while (result3 != null) {
System.out.print(result3.val + " ");
result3 = result3.next;
}
System.out.println(" ");
}
}
Complexity Analysis
-
Time Complexity: The time complexity of the solution is
, where nis the number of nodes in the linked list. This is because we traverse each node exactly once to compute the sums and adjust the links. -
Space Complexity: The space complexity is
. We are not using any extra data structures that grow with the size of the input. We only use a few pointers and variables for the summing and linking process.
🤖 Don't fully get this? Learn it with Claude
Stuck on Merge Nodes in Between Zeros? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Merge Nodes in Between Zeros** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Merge Nodes in Between Zeros** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Merge Nodes in Between Zeros**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Merge Nodes in Between Zeros**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.