<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.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
        idx_to_node = dict()
        latest_idx_for_pre_sum = dict()
        latest_idx_for_pre_sum[0] = 0
        pre_sum = [0]

        dummy = ListNode(0)
        dummy.next = head

        cur = head
        idx = 1
        while cur:
            idx_to_node[idx] = cur
            pre_sum.append(pre_sum[-1] + cur.val)
            latest_idx_for_pre_sum[pre_sum[-1]] = idx
            idx += 1
            cur = cur.next

        # print("idx_to_node", idx_to_node)
        # print("latest_idx_for_pre_sum", latest_idx_for_pre_sum)
        # print("pre_sum", pre_sum, "\n")
        

        current_head = dummy
        pre_sum_idx = 0
        while current_head and pre_sum_idx < len(pre_sum):
            cur_pre_sum = pre_sum[pre_sum_idx]
            latest_here = latest_idx_for_pre_sum[cur_pre_sum]

            # print("current_head", current_head.val, "pre_sum_idx", pre_sum_idx, "cur_pre_sum", cur_pre_sum, "latest_here", latest_here)
            if latest_here > pre_sum_idx:
                current_head.next = idx_to_node[latest_here].next
                pre_sum_idx = latest_here + 1
                current_head = current_head.next
            else:
                pre_sum_idx = latest_here + 1
                current_head = current_head.next

        return dummy.next


28