find max length subarray matching the given sum code example
Example: Find maximum length sub-array having equal number of 0’s and 1’s
def findMaxLenSublist(A):
# create an empty dictionary to store the ending index of the first
# sublist having some sum
dict = {}
# insert `(0, -1)` pair into the set to handle the case when a
# sublist with zero-sum starts from index 0
dict[0] = -1
# `length` stores the maximum length of sublist with zero-sum
length = 0
# stores ending index of the maximum length sublist having zero-sum
ending_index = -1
sum = 0
# Traverse through the given list
for i in range(len(A)):
# sum of elements so far (replace 0 with -1)
sum += -1 if (A[i] == 0) else 1
# if the sum is seen before
if sum in dict:
# update length and ending index of maximum length
# sublist having zero-sum
if length < i - dict.get(sum):
length = i - dict.get(sum)
ending_index = i
# if the sum is seen for the first time, insert the sum with its
# index into the dictionary
else:
dict[sum] = i
# print the sublist if present
if ending_index != -1:
print((ending_index - length + 1, ending_index))
else:
print("No sublist exists")