Binary Subarrays With Sum

medium

Given a binary array nums (each element 0 or 1) and an integer goal, return the number of non-empty subarrays whose sum equals goal.

A subarray is a contiguous part of the array.

Hints

Counting exactly-goal directly is awkward — is there an easier quantity to count?
count(exactly goal) = count(at most goal) - count(at most goal - 1).
Write a sliding-window atMost(k) that adds right-left+1 per step, and call it twice.

Common doubts

atMost(goal) counts every subarray with sum <= goal; subtracting those with sum <= goal-1 removes all but the ones with sum exactly goal.
Once the window [left, right] has sum <= k, every subarray ending at right and starting anywhere in [left, right] also has sum <= k — that's right - left + 1 subarrays.
atMost(-1) must return 0. Then the answer is atMost(0) - 0 = the number of all-zero subarrays, which is correct.

Interview follow-ups

Count how many earlier prefix sums equal current_prefix - goal; that's an alternate O(n) approach that also works for non-binary arrays.
It needs non-negative values so the window sum is monotone as you extend/shrink; binary is a special case. Negative values break the monotonicity.

Fun facts

  • The atMost(k) - atMost(k-1) identity is the single most reused trick for 'exactly k' subarray-counting problems.
  • The very same code, with 'odd number' playing the role of '1', solves Count Number of Nice Subarrays.

Asked at

AmazonGoogleFacebook
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
There are 4 subarrays summing to 2.
Example 2
Input: nums = [0,0,0,0,0], goal = 0
Output: 15
Every one of the 15 non-empty subarrays sums to 0.
Constraints

- 1 <= nums.length <= 3 * 10^4 - nums[i] is 0 or 1. - 0 <= goal <= nums.length

Solve this problem →