---
# System prepended metadata

title: 0930. Binary Subarrays With Sum
tags: [Leetcode, Two Pointers, Sliding Window, Medium]

---

# 0930. Binary Subarrays With Sum
###### tags: `Leetcode` `Medium` `Sliding Window` `Two Pointers` `HashMap` `Prefix Sum`
Link: https://leetcode.com/problems/binary-subarrays-with-sum/
## 思路
### 思路一 $O(N)$ $O(N)$
HashMap + prefixSum
### 思路二 $O(N)$ $O(1)$ (未完)
参考[这里](https://leetcode.com/problems/binary-subarrays-with-sum/discuss/186683/C%2B%2BJavaPython-Sliding-Window-O(1)-Space)
## Code
```python=
class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        sumCnt = Counter()
        sumCnt[0] = 1
        currSum = 0
        ans = 0
        for num in nums:
            currSum += num
            ans += sumCnt[currSum-goal]
            sumCnt[currSum] += 1
        return ans
```