930. Binary Subarrays With Sum
Problem Statement
Given a binary array nums
and an integer goal
, return the number of non-empty subarrays with a sum goal
.
A subarray is a contiguous part of the array.
Example 1:
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
Explanation: The 4 subarrays are bolded and underlined below:
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
[1,0,1,0,1]
Example 2:
Input: nums = [0,0,0,0,0], goal = 0
Output: 15
Constraints:
1 <= nums.length <= 3 * 104
nums[i]
is either0
or1
.0 <= goal <= nums.length
Intuition
Approach 1:
HashMAp and Prefix sum
Intuition
1 0 0 0 1 1
1 1 1 1 )2 3
goal = 2
At prefix sum = 3 we subtract prefix sum = 1
We get sum = 2 arrays
Appraoch 2:
Sliding Window
Atmost k - Atmost k-1
Links
https://leetcode.com/problems/binary-subarrays-with-sum/description/
Video Links
Approach 1:
Hash Map
class Solution {
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
unordered_map<int,int> mp;
int sum=0, ans=0;
mp[0]=1;
for(int i=0; i<nums.size(); i++){
sum += nums[i];
if(mp[sum-goal])
ans += mp[sum-goal];
mp[sum]++;
}
return ans;
}
};
Approach 2:
Sliding Window
class Solution {
public:
int Atmost(vector<int>& nums, int goal){
if(goal < 0) return 0;
int low=0, ans=0;
int sum=goal;
for(int high=0; high<nums.size(); high++){
sum -= nums[high];
while(sum<0)
sum += nums[low++];
ans += high-low+1;
}
return ans;
}
int numSubarraysWithSum(vector<int>& nums, int goal) {
return Atmost(nums, goal) - Atmost(nums, goal-1);
}
};
Approach 3:
Approach 4:
Similar Problems
Last updated