Skip to content

Commit ab4a502

Browse files
authored
Create binary-subarrays-with-sum.py
1 parent 1f152d3 commit ab4a502

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Python/binary-subarrays-with-sum.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Two pointers solution
5+
class Solution(object):
6+
def numSubarraysWithSum(self, A, S):
7+
"""
8+
:type A: List[int]
9+
:type S: int
10+
:rtype: int
11+
"""
12+
result = 0
13+
left, right, sum_left, sum_right = 0, 0, 0, 0
14+
for i, a in enumerate(A):
15+
sum_left += a
16+
while left < i and sum_left > S:
17+
sum_left -= A[left]
18+
left += 1
19+
sum_right += a
20+
while right < i and \
21+
(sum_right > S or (sum_right == S and not A[right])):
22+
sum_right -= A[right]
23+
right += 1
24+
if sum_left == S:
25+
result += right-left+1
26+
return result

0 commit comments

Comments
 (0)