#1171
Remove Zero Sum Consecutive Nodes from Linked List
MediumHash TableLinked ListHash MapArray
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 hashmap to keep track of cumulative sums and their corresponding nodes. This allows us to efficiently find and remove zero-sum sequences in a single pass.
⚙️
Algorithm
5 steps- 1Step 1: Create a dummy node that points to the head of the list.
- 2Step 2: Initialize a hashmap to store cumulative sums and their corresponding nodes.
- 3Step 3: Traverse the list, updating the cumulative sum and checking if it exists in the hashmap.
- 4Step 4: If it exists, remove the nodes between the previous occurrence and the current node.
- 5Step 5: Continue until the end of the list, returning the modified list.
solution.py21 lines
1# Full working Python code
2class ListNode:
3 def __init__(self, val=0, next=None):
4 self.val = val
5 self.next = next
6
7def removeZeroSumSublists(head):
8 dummy = ListNode(0)
9 dummy.next = head
10 current = dummy
11 sum_map = {}
12 total = 0
13 while current:
14 total += current.val
15 if total in sum_map:
16 prev = sum_map[total]
17 prev.next = current.next
18 else:
19 sum_map[total] = current
20 current = current.next
21 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 hashmap storing cumulative sums and their corresponding nodes.
- 1Using cumulative sums helps identify zero-sum sequences efficiently.
- 2A hashmap allows for quick lookups and updates during traversal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.