Find the length of largest subarray with 0 sum | Returns the maximum length ; NOTE : Dictonary in python in implemented as Hash Maps Create an empty hash map ( dictionary ) ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add the current element to the sum ; NOTE : ' in ' operation in dictionary to search key takes O ( 1 ) . Look if current sum is seen before ; else put this sum in dictionary ; test array
def maxLen ( arr ) : NEW_LINE INDENT hash_map = { } NEW_LINE curr_sum = 0 NEW_LINE max_len = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE if arr [ i ] is 0 and max_len is 0 : NEW_LINE INDENT max_len = 1 NEW_LINE DEDENT if curr_sum is 0 : NEW_LINE INDENT max_len = i + 1 NEW_LINE DEDENT if curr_sum in hash_map : NEW_LINE INDENT max_len = max ( max_len , i - hash_map [ curr_sum ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hash_map [ curr_sum ] = i NEW_LINE DEDENT DEDENT return max_len NEW_LINE DEDENT arr = [ 15 , - 2 , 2 , - 8 , 1 , 7 , 10 , 13 ] NEW_LINE print " Length ▁ of ▁ the ▁ longest ▁ 0 ▁ sum ▁ subarray ▁ is ▁ % ▁ d " % maxLen ( arr ) NEW_LINE