> For the complete documentation index, see [llms.txt](https://coding-9.gitbook.io/untitled/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://coding-9.gitbook.io/untitled/sliding-window/medium/930.-binary-subarrays-with-sum.md).

# 930. Binary Subarrays With Sum

## Problem Statement

<br>

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.

&#x20;

**Example 1:**

<pre><code><strong>Input: nums = [1,0,1,0,1], goal = 2
</strong><strong>Output: 4
</strong><strong>Explanation: The 4 subarrays are bolded and underlined below:
</strong><strong>[1,0,1,0,1]
</strong><strong>[1,0,1,0,1]
</strong><strong>[1,0,1,0,1]
</strong><strong>[1,0,1,0,1]
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: nums = [0,0,0,0,0], goal = 0
</strong><strong>Output: 15
</strong></code></pre>

&#x20;

**Constraints:**

* `1 <= nums.length <= 3 * 104`
* `nums[i]` is either `0` or `1`.
* `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
```

{% code title="C++" lineNumbers="true" %}

```cpp
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;
    }
};
```

{% endcode %}

### Approach 2:

```
Sliding Window
```

{% code title="C++" lineNumbers="true" %}

```cpp
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);
    }
};
```

{% endcode %}

### Approach 3:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Approach 4:

```
```

{% code title="C++" lineNumbers="true" %}

```cpp
```

{% endcode %}

### Similar Problems

### <https://leetcode.com/problems/count-number-of-nice-subarrays/description/>
