Binary Subarrays With Sum - Problem

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.

For example, if nums = [1,0,1,0,1] and goal = 2, we need to find all subarrays that sum to 2: [1,0,1], [0,1,0,1], and [1,0,1] (at different positions).

Input & Output

Example 1 — Basic Binary Array
$ Input: nums = [1,0,1,0,1], goal = 2
Output: 4
💡 Note: Four subarrays have sum 2: [1,0,1] at index 0-2, [0,1,0,1] at index 1-4, [1,0,1] at index 2-4, and [0,1] at index 3-4
Example 2 — All Ones
$ Input: nums = [1,1,1], goal = 2
Output: 2
💡 Note: Two subarrays have sum 2: [1,1] at index 0-1 and [1,1] at index 1-2
Example 3 — Goal Zero
$ Input: nums = [0,0,0,0,0], goal = 0
Output: 15
💡 Note: All possible subarrays of zeros sum to 0. With 5 elements, there are 5*6/2 = 15 total subarrays

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • nums[i] is either 0 or 1
  • 0 ≤ goal ≤ nums.length

Visualization

Tap to expand
Binary Subarrays With Sum INPUT Binary Array nums: 1 i=0 0 i=1 1 i=2 0 i=3 1 i=4 goal = 2 Find subarrays with sum=2 [1,0,1] indices 0-2 [0,1,0,1] indices 1-4 [1,0,1] indices 2-4 [1,0,1,0] indices 0-3 ALGORITHM STEPS 1 Initialize HashMap prefixSum: {0: 1} count=0, currSum=0 2 Iterate Array Add nums[i] to currSum Track prefix sums 3 Check Target If (currSum-goal) in map count += map[currSum-goal] 4 Update Map prefixSum[currSum]++ Prefix Sum Map Sum: 0 1 2 3 Cnt: 1 2 2 1 Final state after iteration FINAL RESULT Valid Subarrays Found: [1,0,1] sum=2 (idx 0-2) [1,0,1,0] sum=2 (idx 0-3) [0,1,0,1] sum=2 (idx 1-4) [1,0,1] sum=2 (idx 2-4) Output: 4 OK - 4 subarrays found Time: O(n), Space: O(n) Key Insight: Using a hash map to store prefix sums allows O(1) lookup for subarrays with target sum. If currSum - goal exists in map, we found subarrays ending at current index with sum = goal. The count stored in map tells us how many such subarrays exist (handles duplicates). TutorialsPoint - Binary Subarrays With Sum | Hash Map Approach
Asked in
Facebook 25 Google 20 Amazon 15
67.0K Views
Medium Frequency
~25 min Avg. Time
1.9K 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