LeetCode #930 Medium

Binary Subarrays With Sum

Binary Subarrays With Sum is LeetCode 930 (Medium). Given an array nums where every value is 0 or 1, and an integer goal, return how many non-empty contiguous subarrays have a sum of exactly goal.

  • nums has up to 3 · 10⁴ elements, so checking all of its roughly 4.5 · 10⁸ subarrays one by one is too slow.
  • goal can be 0, and then only runs of zeros count.
Constraints
  • 1 <= nums.length <= 3 * 10⁴
  • nums[i] is either 0 or 1.
  • 0 <= goal <= nums.length
arraysliding-windowprefix-sum
Open on LeetCode ↗
02

Intuition

A sliding window can count subarrays with sum at most k in one pass. No value is negative, so for each right end there is a leftmost start that keeps the sum within k, and every start between it and the right end works too. That is right - left + 1 subarrays counted at once.

Sum exactly goal has no single boundary like that, because zeros let many starts share one sum. So split it into two easy counts:

  • exactly(goal) = atMost(goal) − atMost(goal − 1). Take every subarray with sum up to goal and remove those with sum up to goal − 1; the ones left sum to exactly goal.
How to spot this pattern

"Count subarrays with exactly k of something" over values that never shrink a running total: count "at most k" with a window, do it again for k − 1, and subtract.

03

Approach

Try it first

Before reading on, take [1, 0, 1, 0, 1] and count by hand the subarrays with sum at most 2, then those with sum at most 1. Check that the difference is the answer, 4. Aim for O(n) time and O(1) extra space.

1

Write a helper that counts sums up to k

at_most(k) returns how many subarrays have sum at most k. If k < 0 it returns 0 at once, since no subarray of zeros and ones has a negative sum.

2

Grow the window to the right

Move right across the array and add nums[right] to total. The window nums[left..right] is the longest subarray ending at right that might still fit.

3

Shrink from the left while the sum is too big

While total > k, subtract nums[left] and move left one step. Values are never negative, so dropping elements from the left is the only way to lower the sum, and left never has to move back when right advances.

4

Count every start at once

Add right - left + 1 to the count. Each start from left to right gives a subarray inside the window, and its sum can only be smaller, so all of them fit.

5

Subtract the two counts

Return at_most(goal) - at_most(goal - 1). A subarray with sum exactly goal is counted by the first call and not by the second, and every other subarray is counted by both or by neither.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numSubarraysWithSum(self, nums, goal):
▶3 def at_most(k):
▶4 if k < 0:
▶5 return 0
▶6 left = total = count = 0
▶7 for right, x in enumerate(nums):
▶8 total += x
▶9 while total > k:
▶10 total -= nums[left]
▶11 left += 1
▶12 count += right - left + 1
▶13 return count
▶14 
▶15 return at_most(goal) - at_most(goal - 1)
sum at most2window sum1count so far1nums1001120314left, rightsubarrays ending here+1resultsnone yetadd 1 → sum 1 fits → +1 subarray
right0
window sum1
added1
count1
Pass for sum at most 2. Index 0 joins and the sum is 1, within 2. The only start is index 0: +1, count 1.
sum at most2window sum1count so far3nums1001120314leftrightsubarrays ending here+1+2resultsnone yetadd 0 → sum 1 fits → +2 subarrays
right1
window sum1
added2
count3
Index 1 joins and the sum is 1, within 2. Every start from 0 to 1 fits, because a shorter subarray of zeros and ones cannot sum to more: +2, count 3.
sum at most2window sum2count so far6nums1001120314leftrightsubarrays ending here+1+2+3resultsnone yetadd 1 → sum 2 fits → +3 subarrays
right2
window sum2
added3
count6
Index 2 joins and the sum is 2, within 2. Every start from 0 to 2 fits, because a shorter subarray of zeros and ones cannot sum to more: +3, count 6.
sum at most2window sum2count so far10nums1001120314leftrightsubarrays ending here+1+2+3+4resultsnone yetadd 0 → sum 2 fits → +4 subarrays
right3
window sum2
added4
count10
Index 3 joins and the sum is 2, within 2. Every start from 0 to 3 fits, because a shorter subarray of zeros and ones cannot sum to more: +4, count 10.
sum at most2window sum3count so far10nums1001120314leftrightsubarrays ending here+1+2+3+4resultsnone yetadd 1 → sum 3, over 2
right4
window sum3
count10
Index 4 joins the window and the sum becomes 3, more than 2. The window has to shrink from the left before anything is counted.
sum at most2window sum2count so far14nums1001120314leftrightsubarrays ending here+1+2+3+4+4resultsnone yetdrop index 0 → sum 2 → +4 subarrays
left1
window sum2
added4
count14
Dropping index 0 (a 1) brings the sum down to 2, which fits. Now every start from 1 to 4 gives a subarray with sum at most 2: 4 of them, so the count is 14.
sum at most1window sum1count so far1nums1001120314left, rightsubarrays ending here+1resultsat most 2: 14add 1 → sum 1 fits → +1 subarray
right0
window sum1
added1
count1
Pass for sum at most 1. Index 0 joins and the sum is 1, within 1. The only start is index 0: +1, count 1.
sum at most1window sum1count so far3nums1001120314leftrightsubarrays ending here+1+2resultsat most 2: 14add 0 → sum 1 fits → +2 subarrays
right1
window sum1
added2
count3
Index 1 joins and the sum is 1, within 1. Every start from 0 to 1 fits, because a shorter subarray of zeros and ones cannot sum to more: +2, count 3.
sum at most1window sum2count so far3nums1001120314leftrightsubarrays ending here+1+2resultsat most 2: 14add 1 → sum 2, over 1
right2
window sum2
count3
Index 2 joins the window and the sum becomes 2, more than 1. The window has to shrink from the left before anything is counted.
sum at most1window sum1count so far5nums1001120314leftrightsubarrays ending here+1+2+2resultsat most 2: 14drop index 0 → sum 1 → +2 subarrays
left1
window sum1
added2
count5
Dropping index 0 (a 1) brings the sum down to 1, which fits. Now every start from 1 to 2 gives a subarray with sum at most 1: 2 of them, so the count is 5.
sum at most1window sum1count so far8nums1001120314leftrightsubarrays ending here+1+2+2+3resultsat most 2: 14add 0 → sum 1 fits → +3 subarrays
right3
window sum1
added3
count8
Index 3 joins and the sum is 1, within 1. Every start from 1 to 3 fits, because a shorter subarray of zeros and ones cannot sum to more: +3, count 8.
sum at most1window sum2count so far8nums1001120314leftrightsubarrays ending here+1+2+2+3resultsat most 2: 14add 1 → sum 2, over 1
right4
window sum2
count8
Index 4 joins the window and the sum becomes 2, more than 1. The window has to shrink from the left before anything is counted.
sum at most1window sum2count so far8nums1001120314leftrightsubarrays ending here+1+2+2+3resultsat most 2: 14drop index 1 (0) → sum 2, still over
left2
window sum2
count8
Dropping index 1 removes a 0, so the sum stays at 2. A zero changes nothing, but it has to go before the 1 behind it can. Still more than 1, so keep shrinking.
sum at most1window sum1count so far10nums1001120314leftrightsubarrays ending here+1+2+2+3+2resultsat most 2: 14drop index 2 → sum 1 → +2 subarrays
left3
window sum1
added2
count10
Dropping index 2 (a 1) brings the sum down to 1, which fits. Now every start from 3 to 4 gives a subarray with sum at most 1: 2 of them, so the count is 10.
sum at mostwindow sumcount so farnums1001120314subarrays ending hereresultsat most 2: 14−at most 1: 10=414 − 10 → answer 4
at most 214
at most 110
answer4
Subarrays with sum at most 2, minus those with sum at most 1, leaves exactly the ones with sum 2: 14 − 10 = 4.
05

Prefix sum counts

A subarray ending at the current index sums to goal exactly when the prefix sum before its start equals prefix - goal. seen[p] counts how many prefixes so far equal p, starting with one empty prefix of sum 0. Prefix sums of zeros and ones never exceed n, so a list of size n + 1 is enough.

▶1class Solution:
▶2 def numSubarraysWithSum(self, nums, goal):
▶3 seen = [0] * (len(nums) + 1)
▶4 seen[0] = 1
▶5 prefix = answer = 0
▶6 for x in nums:
▶7 prefix += x
▶8 if prefix >= goal:
▶9 answer += seen[prefix - goal]
▶10 seen[prefix] += 1
▶11 return answer
06

Common pitfalls

Leaving out the k < 0 guard

✗ Wrong
def at_most(k):
    left = total = count = 0
✓ Right
def at_most(k):
    if k < 0:
        return 0
    left = total = count = 0

When goal is 0, the second call is at_most(-1). A sum of 0 is still more than -1, so the shrink loop keeps moving left past the end of the array. [0, 0] with goal = 0 raises an IndexError in Python and reads out of bounds in C++.

Sliding a window for exactly goal

✗ Wrong
while total > goal:
    total -= nums[left]
    left += 1
if total == goal:
    count += 1
✓ Right
return at_most(goal) - at_most(goal - 1)

This counts one subarray per right end, but zeros at the left of the window give several starts with the same sum. [0, 1, 0] with goal = 1 returns 2; the answer is 4: [0, 1], [1], [1, 0] and [0, 1, 0].

Recording a prefix sum before looking it up

✗ Wrong
seen[prefix] += 1
answer += seen[prefix - goal]
✓ Right
answer += seen[prefix - goal]
seen[prefix] += 1

This applies to the prefix-sum version. With goal = 0, recording first lets each position match itself, which counts an empty subarray every time. [0, 0, 0] returns 9 instead of 6.

07

Edge cases

goal is more than the number of ones

No subarray can reach it, and both calls count every subarray, so the difference is 0. [0, 1, 0] with goal = 3 gives 6 - 6 = 0.

All zeros with goal 0

Every subarray counts, so the answer is n(n + 1) / 2. For 3 · 10⁴ zeros that is about 4.5 · 10⁸, which still fits in a 32-bit int.

08

Complexity

Time
O(n)
Space
O(1)
n is the length of nums. Each call moves right across the array once, and left only ever moves forward, so each call is at most 2n steps. Only a few counters are stored.
09

Binary Subarrays With Sum FAQ

How does this relate to Subarray Sum Equals K?

It is the same count on a friendlier input. Subarray Sum Equals K allows negative numbers, so a window's sum can drop as it widens and the at-most window gives wrong counts; the prefix-sum hash map is the tool there. With only zeros and ones, both methods work and the window needs no extra memory.

Can it be done in a single window pass?

Yes. Keep the window's sum at exactly goal, and also track how many zeros sit at its left edge that could be dropped without changing the sum. Each right end then adds that zero count plus one. It is still O(n) and O(1), but the extra counter has to be reset whenever a 1 leaves the window, which is easy to get wrong.