Problem Description
Given the head of a linked list where the list starts and ends with a 0 and has values separated by 0's, merge all nodes between two consecutive 0's by summing their values. The final linked list should only consist of the non-zero summed nodes.
Key Insights
- The linked list always starts and ends with a 0.
- There will be no two consecutive 0's so every group of numbers is clearly delimited.
- You need to sum the values between 0's and create a new node for each sum.
- A simple linear traversal of the list is sufficient to accumulate sums and build the result.
Space and Time Complexity
Time Complexity: O(n) - We traverse each node of the list exactly once. Space Complexity: O(1) (excluding the space for the output list) - Only a few extra variables are used for computation.
Solution
We traverse the linked list using a pointer and keep an accumulator to sum the values found between zeros. When a 0 is encountered and the sum accumulator is non-zero, we create a new node in the result list with this sum and reset the accumulator. We use a dummy node to easily construct and then return the head of the resulting list. This approach ensures that every group of numbers between zeros is merged appropriately.