930. Binary Subarrays With Sum

T: O(n)

S: O(n)

```java
class Solution {
    public int numSubarraysWithSum(int[] nums, int goal) {
        Map<Integer, Integer> map = new HashMap<>(); // prefix sum, count
        map.put(0, 1);
        int prefixSum = 0;
        int result = 0;
        for (int num : nums) {
            prefixSum += num;
            if (map.containsKey(prefixSum - goal)) {
                result += map.get(prefixSum - goal);
            }
            map.put(prefixSum, map.getOrDefault(prefixSum, 0)+1);
        }
        return result;
    }
}

/**
  1 0 1 0 1
0 1 1 2 2 3 

cur - goal

0 1
1 2
2 2
3 1


1 2 3 4 5

0 1
0 2
0 3
0 4
0 5
0

 */
```

Last updated