Skip to content

Commit c570ccd

Browse files
committed
Subarray with given sum
1 parent b7c2db5 commit c570ccd

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Python/GeeksforGeeks/subarray-range-with-given-sum.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,17 @@
3434
Explanation:
3535
Testcase 1: Subarrays with sum -10 are: [10, 2, -2, -20], [2, -2, -20, 10] and [-20, 10].
3636
"""
37-
def countSubSum(arr,target):
38-
count,summ,d = 0,0,{0:1}
39-
for i in arr:
40-
summ += i
41-
if summ - target in d:
42-
count += d[summ-target]
43-
d[summ] = d.get(summ,0) + 1
44-
return count
37+
def subArraySum(arr,target):
38+
summ = 0
39+
d= {}
40+
d[0] = 0
41+
for i in range(len(arr)):
42+
summ += arr[i]
43+
difference = summ - target
44+
if difference in d:
45+
return [d[difference]+1,i+1]
46+
d[summ] = i+1
47+
return [-1]
4548

4649
for _ in range(int(input())):
4750
n = int(input())

0 commit comments

Comments
 (0)