There is a simpler approach. It requires no extra memory as well. Just have two pointers and a sliding window, whenever the current sum equals zero remove the window in O(1). The overall time complexity will still be O(n2) but will require no extra memory also it is easier to implement.
class Solution:
def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(next=head)
left = dummy
while left.next:
right = left.next
cur_sum = 0
while right:
cur_sum += right.val
if cur_sum == 0:
break
right = right.next
if cur_sum == 0:
left.next = right.next
continue
left = left.next
return dummy.next
mufaddaltatiwala
Did you come up with this solution by yourself, because this problem was really hard for me