930. Binary Subarrays With Sum
Input: A = [1,0,1,0,1], S = 2
Output: 4
Explanation:
The 4 subarrays are bolded below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]// Pre-Sum
int numSubarraysWithSum(vector<int>& A, int S) { // time: O(n); space: O(n)
unordered_map<int, int> mp;
++mp[0];
int presum = 0, res = 0;
for (int num : A) {
presum += num;
res += mp[presum - S];
++mp[presum];
}
return res;
}Last updated