Given a binary array nums (containing only 0s and 1s) and an integer goal, your task is to find the number of non-empty contiguous subarrays whose elements sum exactly to the goal.
A subarray is a contiguous part of the array. For example, in array [1,0,1,0,1], the subarrays [1,0], [0,1,0], and [1,0,1,0,1] are all valid contiguous subarrays.
Your goal: Count how many such subarrays exist that sum to exactly goal.
Example: If nums = [1,0,1,0,1] and goal = 2, we need to find subarrays that sum to 2. The valid subarrays are [1,0,1] at indices 0-2, and [0,1,0,1] at indices 1-4, giving us a total count of 4 subarrays.
Input & Output
Constraints
- 1 β€ nums.length β€ 3 Γ 104
- nums[i] is either 0 or 1
- 0 β€ goal β€ nums.length