We want to count the number of subarrays whose sum is exactly goal. By using a prefix sum and a hash map to count the number of times each prefix sum occurs, we can efficiently count the number of valid subarrays ending at each index.
classSolution {
public:int numSubarraysWithSum(vector<int>& nums, int goal) {
unordered_map<int, int> cnt;
cnt[0] =1;
int sum =0, ans =0;
for (int x : nums) {
sum += x;
ans += cnt[sum - goal];
cnt[sum]++;
}
return ans;
}
};
classSolution {
publicintnumSubarraysWithSum(int[] nums, int goal) {
Map<Integer, Integer> cnt =new HashMap<>();
cnt.put(0, 1);
int sum = 0, ans = 0;
for (int x : nums) {
sum += x;
ans += cnt.getOrDefault(sum - goal, 0);
cnt.put(sum, cnt.getOrDefault(sum, 0) + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funnumSubarraysWithSum(nums: IntArray, goal: Int): Int {
val cnt = mutableMapOf(0 to 1)
var sum = 0var ans = 0for (x in nums) {
sum += x
ans += cnt.getOrDefault(sum - goal, 0)
cnt[sum] = cnt.getOrDefault(sum, 0) + 1 }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defnumSubarraysWithSum(self, nums: list[int], goal: int) -> int:
from collections import defaultdict
cnt: dict[int, int] = defaultdict(int)
cnt[0] =1 s = ans =0for x in nums:
s += x
ans += cnt[s - goal]
cnt[s] +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnnum_subarrays_with_sum(nums: Vec<i32>, goal: i32) -> i32 {
use std::collections::HashMap;
letmut cnt = HashMap::new();
cnt.insert(0, 1);
let (mut sum, mut ans) = (0, 0);
for x in nums {
sum += x;
ans +=*cnt.get(&(sum - goal)).unwrap_or(&0);
*cnt.entry(sum).or_insert(0) +=1;
}
ans
}
}