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 ProblemFind count of subarrays that sum to goal10101goal = 2[1,0,1] = 2 ✓[0,1,0,1] = 2 ✓[1,0,1] = 2 ✓[0,1] = 1 ✗Answer: 4 subarrays found
Understanding the Visualization
1
Input
Binary array [1,0,1,0,1] with goal=2
2
Process
Find all contiguous subarrays that sum to goal
3
Output
Count of valid subarrays = 4
Key Takeaway
🎯 Key Insight: Use prefix sums to transform the problem into finding pairs of sums that differ by goal
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