<p>Given the <code>head</code> of a linked list, we repeatedly delete consecutive sequences of nodes that sum to <code>0</code> until there are no such sequences.</p>

<p>After doing so, return the head of the final linked list.&nbsp; You may return any such answer.</p>

<p>&nbsp;</p>
<p>(Note that in the examples below, all sequences are serializations of <code>ListNode</code> objects.)</p>

<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> head = [1,2,-3,3,1]
<strong>Output:</strong> [3,1]
<strong>Note:</strong> The answer [1,2,1] would also be accepted.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> head = [1,2,3,-3,4]
<strong>Output:</strong> [1,2,4]
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> head = [1,2,3,-3,-2]
<strong>Output:</strong> [1]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The given linked list will contain between <code>1</code> and <code>1000</code> nodes.</li>
	<li>Each node in the linked list has <code>-1000 &lt;= node.val &lt;= 1000</code>.</li>
</ul>

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeZeroSumSublists(ListNode* head) {
        // here we will be using map solution to solve this problem
        // map will be storing the key and value here key will be the prefix sum and value will be the node address
        unordered_map<int, ListNode*>m;
        int sum=0;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        m[0] = dummy;   // initialzing the map
        ListNode* temp = head;
        while(temp!=NULL)
        {
            sum+= temp->val;
            

            if(m.find(sum)!=m.end())   // if sum exists previously
            {
                // we have to erase the sum in between from map and detach the list 
                ListNode* temp2 = temp; // next same sum node
                ListNode* temp1 = m[sum];  // prev node whose sum is equal

                ListNode* curr = temp1->next;
                int currsum = sum;
                while(curr!=temp2)
                {
                    currsum+= curr->val;
                    m.erase(currsum);    // erasing in between nodes sum stored in map
                    curr = curr->next;
                }
                temp1->next = temp2->next;  // we have attached at new location 

            }
            else
            {
                m[sum] = temp;
            }
            temp =temp->next;
        }
        return dummy->next;

        
    }
};
16500