#2181
Merge Nodes in Between Zeros
MediumLinked ListSimulationTwo PointersLinked List Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a single pass through the linked list to sum values between zeros, thus improving efficiency. We maintain a running sum and only create new nodes when we encounter a zero.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a dummy node to help build the new list and a pointer to traverse the original list.
- 2Step 2: Use a variable to keep track of the sum of values between zeros.
- 3Step 3: When a zero is encountered, if the sum is greater than zero, create a new node with the sum and link it to the new list.
- 4Step 4: Reset the sum and continue until the end of the list.
solution.py20 lines
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6def mergeNodes(head):
7 current = head.next
8 dummy = ListNode(0)
9 tail = dummy
10 sum_nodes = 0
11 while current:
12 if current.val == 0:
13 if sum_nodes > 0:
14 tail.next = ListNode(sum_nodes)
15 tail = tail.next
16 sum_nodes = 0
17 else:
18 sum_nodes += current.val
19 current = current.next
20 return dummy.nextℹ
Complexity note: The time complexity is O(n) because we traverse the list only once. The space complexity is O(n) due to the new linked list we create to store the sums.
- 1The problem requires careful handling of linked list nodes and understanding of how to traverse and modify them.
- 2Using a dummy node simplifies the process of building a new linked list.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.