Remove Zero Sum Consecutive Nodes from Linked List

Problem Id: 1171 Difficulty: Medium


Intuition

Solution


class Solution:
    def removeZeroSumSublists(self, head: ListNode) -> ListNode:
        prev = set()
        prev.add(0)
        s = 0
        index = head
        while index:
            s += index.val
            if s in prev:
                if s == 0:
                    return self.removeZeroSumSublists(index.next)
                last = prev
                j = head
                s2 = 0
                while j:
                    s2 += j.val
                    if s2 == s:
                        j.next = index.next
                        return self.removeZeroSumSublists(head)
                    j = j.next
            prev.add(s)
            index = index.next
        return head