Binary Subarrays With Sum - Problem
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
example_1.py β Basic Case
$
Input:
{"nums": [1,0,1,0,1], "goal": 2}
βΊ
Output:
4
π‘ Note:
The 4 subarrays with sum 2 are: [1,0,1] at indices (0,2), [0,1] at indices (1,2), [1] at index (2), and [0,1,0,1] at indices (1,4). Note that [1] at index (4) also has sum 1, not 2.
example_2.py β Goal Zero
$
Input:
{"nums": [0,0,0,0,0], "goal": 0}
βΊ
Output:
15
π‘ Note:
Every subarray sums to 0. With 5 elements, we have 5+4+3+2+1 = 15 possible subarrays: 5 single elements, 4 pairs, 3 triplets, 2 quadruplets, and 1 quintuplet.
example_3.py β No Valid Subarrays
$
Input:
{"nums": [1,1,1], "goal": 5}
βΊ
Output:
0
π‘ Note:
The maximum possible sum is 3 (all elements), which is less than the goal of 5. Therefore, no subarrays can sum to 5.
Constraints
- 1 β€ nums.length β€ 3 Γ 104
- nums[i] is either 0 or 1
- 0 β€ goal β€ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Track Your Wealth
Keep a running total of coins collected (prefix sum)
2
Remember Past Wealth
Record every wealth level you've achieved in your logbook (hash map)
3
Find Valid Routes
At each step, check if you've been at wealth level (current - goal) before
4
Count Treasures
Each time you find a match, you've discovered valid treasure routes!
Key Takeaway
π― Key Insight: By tracking all wealth levels we've seen before, we can instantly identify when we've found a treasure route by checking if we've been at wealth level (current - goal) previously!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code