Skip to content

930. Binary Subarrays With Sum 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int numSubarraysWithSum(vector<int>& A, int S) {
    int ans = 0;
    int prefix = 0;
    unordered_map<int, int> count{{0, 1}};

    for (int a : A) {
      prefix += a;
      if (count.count(prefix - S))
        ans += count[prefix - S];
      ++count[prefix];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int numSubarraysWithSum(int[] A, int S) {
    int ans = 0;
    int prefix = 0;
    Map<Integer, Integer> count = new HashMap<>();

    count.put(0, 1);

    for (int a : A) {
      prefix += a;
      if (count.containsKey(prefix - S))
        ans += count.get(prefix - S);
      count.put(prefix, count.getOrDefault(prefix, 0) + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def numSubarraysWithSum(self, A: List[int], S: int) -> int:
    ans = 0
    prefix = 0
    count = collections.Counter({0: 1})

    for a in A:
      prefix += a
      ans += count[prefix - S]
      count[prefix] += 1

    return ans