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
πŸ—ΊοΈ Treasure Hunter's Map: Find Routes with 2 Gold CoinsπŸͺ™Wealth: 1β­•Wealth: 1πŸͺ™Wealth: 2β­•Wealth: 2πŸͺ™Wealth: 3πŸ“š Hunter's Logbook (Hash Map)Position 0: Wealth 0 β†’ Count: 1 (starting point)Position 1: Wealth 1 β†’ Count: 1Position 3: Wealth 2 β†’ Looking for (2-2=0) βœ“ Found it!This means route from start to position 3 has 2 coins!🎯 Treasure Found!Every time we find (current_wealth - goal) in our logbook,we've discovered a valid treasure route! πŸ—ΊοΈβ†’πŸ†
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!
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 25
42.3K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen