<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>

def numSubarraysForZero(nums: List[int]) -> int:
    i = 0
    count = 0
    while i < len(nums):
        if nums[i] == 1:
            i += 1
            continue
        
        length = 0
        while i < len(nums) and nums[i] == 0:
            i += 1
            length += 1
        count += (length * (length - 1) // 2) + length
    return count



class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        if goal == 0:
            return numSubarraysForZero(nums)
        
        onesIndexes = []
        for i, n in enumerate(nums):
            if n == 1:
                onesIndexes.append(i)
        
        count = 0
        for i in range(len(onesIndexes) - goal + 1):
            firstIndex = onesIndexes[i]
            beforeIndex = firstIndex-1
            while beforeIndex >= 0 and nums[beforeIndex] == 0:
                beforeIndex -= 1
            numZeroesBefore = firstIndex - (beforeIndex + 1)

            lastIndex = onesIndexes[i + goal - 1]
            afterIndex = lastIndex + 1
            while afterIndex < len(nums) and nums[afterIndex] == 0:
                afterIndex += 1
            numZeroesAfter = (afterIndex - 1) - lastIndex
            count += (numZeroesBefore + 1) * (numZeroesAfter + 1)
        return count

18400