forked from devAmoghS/Python-Interview-Problems-for-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhasZeroSumSubArray.py
38 lines (28 loc) · 859 Bytes
/
hasZeroSumSubArray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# This method returns the sum of numbers
# present till each index
def getPrefixArray(arr):
return [sum(arr[:i]) for i in range(1, len(arr)+1)]
# This method will create a mapping of numbers
# and the indices they are present at
def getIndexMap(arr):
indexMap = {}
for i in range(len(arr)):
if arr[i] not in indexMap.keys():
indexMap[arr[i]] = [i,]
else:
indexMap[arr[i]].append(i)
return indexMap
# This method will create the sum prefix of the
# current array, if the sum is repeating, then
# there is a zero sum sub array
def hasZeroSum(arr):
prefixArr = getPrefixArray(arr)
sumAtIndexMap = getIndexMap(prefixArr)
for v in sumAtIndexMap.values():
if len(v) > 1:
return True
break
return False
ipArray = [1, 4, -2, -2, 5, -4, 3]
hasZeroSumTrue = hasZeroSum(ipArray)
print(hasZeroSumTrue)