<p>Given a binary array <code>nums</code> and an integer <code>goal</code>, return <em>the number of non-empty <strong>subarrays</strong> with a sum</em> <code>goal</code>.</p>

<p>A <strong>subarray</strong> is a contiguous part of the array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

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

<p><strong class="example">Example 2:</strong></p>

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

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
	<li><code>0 &lt;= goal &lt;= nums.length</code></li>
</ul>

class Solution {
public:
#define ll long long
    // int solve(vector<int>& nums, int k) {
    //     int n = nums.size();
    //     int i = 0;
    //     int j = 0;
    //     ll sum = 0;
    //     int ans = 0;
    //     while (j < n) {
    //         sum += nums[j];

    //         while (sum > k && i<=j) {
    //             sum -= nums[i];
    //             i++;
    //         }

    //         ans += (j - i + 1);
    //         j++;
    //     }
    //     return ans;
    // }

    int solve(vector<int>& nums, int k) {
    unordered_map<int, int> prefixSumCount;
    int sum = 0;
    int ans = 0;

    // Initially, there's one way to get a sum of 0 (the empty subarray).
    prefixSumCount[0] = 1;

    for (int num : nums) {
        // Update the running sum.
        sum += num;

        // Check if there is a prefix sum that would make the current subarray sum equal to k.
        if (prefixSumCount.find(sum - k) != prefixSumCount.end()) {
            ans += prefixSumCount[sum - k];
        }

        // Store the current prefix sum in the map.
        prefixSumCount[sum]++;
    }

    return ans;
}
    
    int numSubarraysWithSum(vector<int>& nums, int goal) {
        return solve(nums, goal);
    }
};
38700