{x}
blog image

Merge Nodes in Between Zeros

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.

 

Example 1:

Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation: 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.

Example 2:

Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation: 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.

 

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 Explanation: Merge Nodes in Between Zeros

This problem involves manipulating a linked list where nodes with value 0 act as separators between groups of nodes. The goal is to merge the nodes between each pair of 0s into a single node representing the sum of their values.

Approach: Iterative Traversal and Summation

The most efficient approach is an iterative traversal of the linked list. We maintain a running sum and create a new linked list to store the results.

  1. Initialization: Create a dummy node dummy to simplify handling the head of the new list. We'll also have a tail pointer to track the end of the new list and a sum variable to accumulate values between zeros.

  2. Iteration: Iterate through the input linked list starting from the node after the initial 0.

  3. Summation: If the current node's value is not 0, add it to the sum.

  4. Zero Encountered: If a node with value 0 is encountered:

    • Create a new node in the result list with the accumulated sum.
    • Reset the sum to 0.
    • Advance the tail pointer to the newly created node.
  5. Final Node: After the loop, there might be a remaining sum. Handle this by creating a final node if necessary.

  6. Return: Return the next node of the dummy node, which is the head of the modified linked list.

Time and Space Complexity

  • Time Complexity: O(N), where N is the number of nodes in the input linked list. We traverse the list once.
  • Space Complexity: O(M), where M is the number of zero separators in the input list. This is because we create a new linked list with at most M nodes (one for each sum). In the worst case, M could be close to N/2, but it's still linear with respect to the input size.

Code Implementation (Python)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
 
class Solution:
    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode(0)  # Dummy node
        tail = dummy
        current_sum = 0
        curr = head.next  # Start from the node after the initial 0
 
        while curr:
            if curr.val != 0:
                current_sum += curr.val
            else:
                new_node = ListNode(current_sum)
                tail.next = new_node
                tail = new_node
                current_sum = 0
            curr = curr.next
 
        return dummy.next  # Return the head of the new list
 

The code in other languages (Java, C++, Go, TypeScript, Rust, C) follows a very similar structure, adapting the syntax and data structures specific to each language. The core logic of iterative traversal, summation, and new node creation remains consistent across all implementations.