Skip to content

Commit 191da07

Browse files
author
Amogh Singhal
authored
Create hasZeroSumSubArray.py
1 parent 2cf23f3 commit 191da07

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

hasZeroSumSubArray.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# This method returns the sum of numbers
2+
# present till each index
3+
4+
def getPrefixArray(arr):
5+
return [sum(arr[:i]) for i in range(1, len(arr)+1)]
6+
7+
# This method will create a mapping of numbers
8+
# and the indices they are present at
9+
10+
def getIndexMap(arr):
11+
indexMap = {}
12+
13+
for i in range(len(arr)):
14+
if arr[i] not in indexMap.keys():
15+
indexMap[arr[i]] = [i,]
16+
else:
17+
indexMap[arr[i]].append(i)
18+
19+
return indexMap
20+
21+
# This method will create the sum prefix of the
22+
# current array, if the sum is repeating, then
23+
# there is a zero sum sub array
24+
25+
def hasZeroSum(arr):
26+
prefixArr = getPrefixArray(arr)
27+
sumAtIndexMap = getIndexMap(prefixArr)
28+
29+
for v in sumAtIndexMap.values():
30+
if len(v) > 1:
31+
return True
32+
break
33+
return False
34+
35+
36+
ipArray = [1, 4, -2, -2, 5, -4, 3]
37+
hasZeroSumTrue = hasZeroSum(ipArray)
38+
print(hasZeroSumTrue)

0 commit comments

Comments
 (0)