function to print all subarrays with a zero sum in a given array

Solutions on MaxInterview for function to print all subarrays with a zero sum in a given array by the best coders in the world

showing results for - "function to print all subarrays with a zero sum in a given array"
Bruno
04 Jan 2021
1# Utility function to insert <key, value> into the dictionary
2def insert(dict, key, value):
3 
4    # if the key is seen for the first time, initialize the list
5    dict.setdefault(key, []).append(value)
6 
7 
8# Function to print all sublists with a zero-sum present in a given list
9def printallSublists(A):
10 
11    # create an empty dictionary to store the ending index of all
12    # sublists having the same sum
13    dict = {}
14 
15    # insert `(0, -1)` pair into the dictionary to handle the case when
16    # sublist with zero-sum starts from index 0
17    insert(dict, 0, -1)
18 
19    sum = 0
20 
21    # traverse the given list
22    for i in range(len(A)):
23 
24        # sum of elements so far
25        sum += A[i]
26 
27        # if the sum is seen before, there exists at least one
28        # sublist with zero-sum
29        if sum in dict:
30 
31            list = dict.get(sum)
32 
33            # find all sublists with the same sum
34            for value in list:
35                print("Sublist is", (value + 1, i))
36 
37        # insert (sum so far, current index) pair into the dictionary
38        insert(dict, sum, i)