-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem-1171.cpp
37 lines (34 loc) · 994 Bytes
/
Problem-1171.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//Problem - 1171
// https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/
// Time Complexity O(n) and O(n) space
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
if(!head)
return NULL;
ListNode dummy(0) ;
dummy.next = head;
head = &dummy;
unordered_map <int, ListNode*> um;
int sum = 0;
ListNode* curr = head;
while(curr) {
sum += curr->val;
if(um.find(sum) != um.end()) {
int tempSum = sum;
ListNode* temp = um[sum]->next;
while(temp != curr) {
tempSum += temp->val;
um.erase(tempSum);
temp = temp->next;
}
um[sum]->next = curr->next;
}
else {
um[sum] = curr;
}
curr = curr->next;
}
return head->next;;
}
};