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
18
class Solution {
 public:
  int numSubarraysWithSum(vector<int>& nums, int goal) {
    int ans = 0;
    int prefix = 0;
    // {prefix: number of occurrence}
    unordered_map<int, int> count{{0, 1}};

    for (const int num : nums) {
      prefix += num;
      if (const auto it = count.find(prefix - goal); it != count.cend())
        ans += it->second;
      ++count[prefix];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int numSubarraysWithSum(int[] nums, int goal) {
    int ans = 0;
    int prefix = 0;
    // {prefix: number of occurrence}
    Map<Integer, Integer> count = new HashMap<>();
    count.put(0, 1);

    for (final int num : nums) {
      prefix += num;
      final int key = prefix - goal;
      if (count.containsKey(key))
        ans += count.get(key);
      count.merge(prefix, 1, Integer::sum);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:
    ans = 0
    prefix = 0
    # {prefix: number of occurrence}
    count = collections.Counter({0: 1})

    for num in nums:
      prefix += num
      ans += count[prefix - goal]
      count[prefix] += 1

    return ans