Skip to content

Commit 1e30010

Browse files
committed
Added Python solution for "Binary Subarrays With Sum"
1 parent 3915ba2 commit 1e30010

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Python/Binary Subarrays With Sum.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from collections import defaultdict
2+
from itertools import accumulate
3+
from typing import List
4+
5+
6+
class Solution:
7+
"""
8+
Time: O(n)
9+
Memory: O(n)
10+
"""
11+
12+
def numSubarraysWithSum(self, nums: List[int], target: int) -> int:
13+
prefix_sums = defaultdict(int)
14+
prefix_sums[0] = 1
15+
16+
sub_arrays = 0
17+
for prefix in accumulate(nums):
18+
sub_arrays += prefix_sums[prefix - target]
19+
prefix_sums[prefix] += 1
20+
21+
return sub_arrays
0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)