Binary Subarrays With Sum
Explanation & Solution
Description
Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum equal to goal.
A subarray is a contiguous part of the array.
Output: 4
Explanation: The 4 subarrays with sum equal to 2 are: [1,0,1], [1,0,1,0], [0,1,0,1], [1,0,1].
Constraints
1 <= nums.length <= 3 * 10^4nums[i]is either0or10 <= goal <= nums.length
Approach
Sliding Window pattern
1. The "Exactly Goal" = "At Most Goal" minus "At Most Goal-1" Trick
- Counting subarrays with exactly a given sum directly with a sliding window is difficult.
- Instead, compute:
atMost(goal) - atMost(goal - 1). atMost(goal)counts all subarrays with sum 0, 1, 2, ..., or goal.- Subtracting
atMost(goal - 1)removes subarrays with a sum less than goal, leaving exactly those with sum equal to goal.
2. The atMost Helper
- If
g < 0, return 0 immediately (no valid subarrays possible). - Initialize
left = 0,sum = 0(running sum of the window), andcount = 0. - Iterate
rightacross the array. Addnums[right]tosum.
3. Shrink When Sum Exceeds Goal
- While
sum > g, subtractnums[left]fromsumand incrementleft. - This contracts the window until the sum is within the allowed limit.
4. Count Valid Subarrays
- After adjusting, every subarray ending at
rightand starting from any index in[left, right]has sum at mostg. - Add
right - left + 1tocount.
5. Combine the Results
- Return
atMost(goal) - atMost(goal - 1)for the final answer.
🧠 Key Insight
The atMost subtraction pattern is essential for "exactly K" problems on binary arrays. Since all values are 0 or 1, the sum increases monotonically as the window expands, which is exactly the property needed for the sliding window to work correctly. The solution runs in O(n) time (two linear passes) and O(1) space. The g < 0 guard in atMost handles the edge case where goal = 0 elegantly, since atMost(-1) returns 0.
Visualization
Press ▶ or use ← → to step through