<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:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        # maximize length of subarray
        # 00000.... XXX .... 00000
        # see how many 0s on either side
        # right side is not necessary, but how about left side? use prefix sum

        # key is starting index of a block of 0, value is length of block
        prefix = defaultdict(int)
        zblock = False
        start = 0
        last_block = -1
        # 0110010
        for i in range(len(nums)):
            if nums[i] == 0:
                if not zblock:
                    # start of a new zero-block
                    prefix[i] += 1
                    last_block = i
                    zblock = True
                else:
                    prefix[last_block] += 1
            
            else:
                # end of zero-block
                zblock = False
        
        # use sliding window
        i = 0
        j = 0
        count = 0
        # if there are 2 zeros on left side 00XX
        # then there are (2 + 1) subarrays
        # next iteration: 00XX0 -> additional (2 + 1) new subarrays
        subarrays = 0
        while j < len(nums):
            count += nums[j]
            while count > goal and i <= j:
                count -= nums[i]
                i += 1
            if count == goal:
                if goal == 0 and i <= j:
                    subarrays += (prefix[i] * (prefix[i] + 1)) // 2
                    while j < len(nums) and nums[j] == 0:
                        j += 1
                    j -= 1
                if goal != 0:
                    left_side = 1 + prefix[i]
                    subarrays += left_side
            j += 1
        return subarrays
                




        





19700