aboutsummaryrefslogtreecommitdiff
path: root/binary_subarr_sum.py
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /binary_subarr_sum.py
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'binary_subarr_sum.py')
-rw-r--r--binary_subarr_sum.py30
1 files changed, 30 insertions, 0 deletions
diff --git a/binary_subarr_sum.py b/binary_subarr_sum.py
new file mode 100644
index 0000000..75a9df7
--- /dev/null
+++ b/binary_subarr_sum.py
@@ -0,0 +1,30 @@
+# 930. Binary Subarrays With Sum
+import collections
+
+"""
+given a binary array 'nums' and an integer 'goal', return the number o
+non-empty subarrays with a sum 'goal'. a subarray is a contiguous part of the
+array
+ """
+
+
+class Solution(object):
+ def numSubarraysWithSum(self, nums, goal):
+ """
+ :type nums: List[int]
+ :type goal: int
+ :rtype: int
+ """
+ c = collections.Counter({0: 1})
+ psum = ans = 0
+ for i in nums:
+ psum += i
+ ans += c[psum - goal]
+ c[psum] += 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.numSubarraysWithSum(nums=[1, 0, 1, 0, 1], goal=2))
+ print(obj.numSubarraysWithSum(nums=[0, 0, 0, 0, 0], goal=0))