<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:
        if set(nums) == {0} and goal == 0:  # Special case.
            total_nums = len(nums)
            return (1 + total_nums) * total_nums // 2
        
        prefix_sums = []
        for num in nums:
            if not prefix_sums:  # 1st int.
                prefix_sums.append(num)
                continue
            prefix_sums.append(prefix_sums[-1] + num)

        count, queue, queue_len = 0, [], 0  # (Prefix sum end idx) increasing monotonic queue.
        for end_idx, prefix_sum in enumerate(prefix_sums):
            # Subarrays from (queue[0] + 1)th idx to (end_idx)th idx.
            # If a start idx & end idx exceed goal, so will a bigger end idx with this start idx.
            while queue and prefix_sum - prefix_sums[queue[0]] > goal:
                queue.pop(0)
                queue_len -= 1

            queue_idx = 0
            while queue_idx < queue_len and prefix_sum - prefix_sums[queue[queue_idx]] == goal:
                count += 1
                queue_idx += 1
            
            if prefix_sum == goal:  # Subarray from 0th idx to (end_idx)th idx.
                count += 1

            queue.append(end_idx)
            queue_len += 1

        return count

19000