Binary Subarrays With Sum
Given a binary array nums (each element 0 or 1) and an integer goal, return the number of non-empty subarrays whose elements sum to exactly goal. Subarrays are contiguous and different index ranges count separately even if their contents match.
Open official problem prompt ↗Count how many contiguous stretches of the binary array add up to exactly goal.
Reading a ledger of running balances: to count every span that changed the balance by exactly goal, at each new balance you ask how many past balances were exactly goal lower.
- Input
- nums = [1, 0, 1, 0, 1], goal = 2
- Output
- 4
- Why
- Four index ranges sum to 2: (0-2), (0-3), (1-4) and (2-4)
1 <= nums.length <= 3 * 10^4nums[i] is 0 or 10 <= goal <= nums.length