
You are given a binary array nums (containing only 0s and 1s) and an integer goal. Your task is to find the total number of non-empty subarrays whose elements sum up to the goal.
A subarray is a contiguous part of the array.
The first line contains a single integer N, the number of elements in the array.
The second line contains the integer goal.
The third line contains N space-separated integers, representing the elements of the nums array.
Your function should return a single integer representing the total count of valid subarrays. The runner code will handle printing.
A brute-force solution that checks the sum of all possible O(N^2) subarrays will be too slow for the given constraints. An efficient O(N) solution is required. This can be achieved using a hash map to store the frequencies of prefix sums encountered so far.
5
2
1 0 1 0 1
4
The 4 subarrays that sum to 2 are:
[1, 0, 1] (from index 0 to 2)
[1, 0, 1, 0] (from index 0 to 3)
[0, 1, 0, 1] (from index 1 to 4)
[1, 0, 1] (from index 2 to 4)
5
0
0 0 0 0 0
15
Any subarray consisting only of 0s will have a sum of 0. The number of non-empty subarrays in an array of size 5 is 5 * (5 + 1) / 2 = 15.
The expected time complexity is O(N).
1 <= nums.length <= 3 * 10^4
nums[i] is either 0 or 1.
0 <= goal <= nums.length
Time Limit: 1 sec