Leetcode Problem 1171. Remove Zero Sum Consecutive Nodes from Linked List
1171. Remove Zero Sum Consecutive Nodes from Linked List
Leetcode Solutions
Using Prefix Sum and HashMap
Create a dummy node with value 0 and point its next to head.
Initialize a hashmap to store prefix sum and corresponding node.
Initialize prefix sum to 0.
Traverse the linked list from the dummy node.
a. Update the prefix sum by adding the current node's value.
b. Check if the prefix sum is in the hashmap.
i. If it is, it means we found a zero-sum sublist. Set the next of the node in hashmap to current node's next.
ii. Remove all prefix sums from the hashmap that are part of the zero-sum sublist.
c. If the prefix sum is not in the hashmap, add it with the current node.
Move to the next node and repeat steps 4a to 4c.
Return the next of the dummy node, which is the head of the modified list.