|  | 
|  | 1 | +/* | 
|  | 2 | +Author : Saransh Bangar | 
|  | 3 | +Date : 12/03/2024 | 
|  | 4 | +Problem : Remove Zero Sum Consecutive Nodes from Linked List | 
|  | 5 | +Difficulty : Medium  | 
|  | 6 | +Problem Link : https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/description/ | 
|  | 7 | +Video Solution : NA | 
|  | 8 | +*/ | 
|  | 9 | + | 
|  | 10 | + | 
|  | 11 | +/** | 
|  | 12 | + * Definition for singly-linked list. | 
|  | 13 | + * struct ListNode { | 
|  | 14 | + * int val; | 
|  | 15 | + * ListNode *next; | 
|  | 16 | + * ListNode() : val(0), next(nullptr) {} | 
|  | 17 | + * ListNode(int x) : val(x), next(nullptr) {} | 
|  | 18 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} | 
|  | 19 | + * }; | 
|  | 20 | + */ | 
|  | 21 | +class Solution { | 
|  | 22 | +public: | 
|  | 23 | + ListNode* removeZeroSumSublists(ListNode* head) | 
|  | 24 | + { | 
|  | 25 | + ListNode* front = new ListNode(0, head); | 
|  | 26 | + ListNode* current = front; | 
|  | 27 | + int prefixSum = 0; | 
|  | 28 | + unordered_map<int, ListNode*> prefixSumToNode; | 
|  | 29 | + prefixSumToNode[0] = front; | 
|  | 30 | + | 
|  | 31 | + while (current != nullptr) | 
|  | 32 | + { | 
|  | 33 | + prefixSum += current->val; | 
|  | 34 | + prefixSumToNode[prefixSum] = current; | 
|  | 35 | + current = current->next; | 
|  | 36 | + } | 
|  | 37 | + | 
|  | 38 | + prefixSum = 0; | 
|  | 39 | + current = front; | 
|  | 40 | + | 
|  | 41 | + while (current != nullptr) | 
|  | 42 | + { | 
|  | 43 | + prefixSum += current->val; | 
|  | 44 | + current->next = prefixSumToNode[prefixSum]->next; | 
|  | 45 | + current = current->next; | 
|  | 46 | + } | 
|  | 47 | + return front->next; | 
|  | 48 | + } | 
|  | 49 | +}; | 
0 commit comments