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.
numshas up to 3 · 10⁴ elements, so checking all of its roughly 4.5 · 10⁸ subarrays one by one is too slow.goalcan be 0, and then only runs of zeros count.
- 1 <= nums.length <= 3 * 10⁴
- nums[i] is either 0 or 1.
- 0 <= goal <= nums.length
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
goaland remove those with sum up togoal − 1; the ones left sum to exactlygoal.
"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.
Approach
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.
Two ways to solve it
Count subarrays with sum up to goal, then up to goal - 1, and subtract.
- Memory: three counters.
- Needs: no negative values, so a window's sum only grows as it widens.
For each prefix sum, add how many earlier prefixes equal prefix - goal.
- One pass: no helper, no subtraction.
- General: works with any values; here an array of size n + 1 replaces the hash map.
Both run in O(n). The window wins on memory and is the trick this problem is known for; the prefix-sum count is the general tool that also works when values can be negative. The steps, code and live demo follow the window; the prefix-sum code comes after the demo.
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.
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.
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.
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.
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.
Code in Python, C++ and Java
left off the end of the array.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.
Common pitfalls
Leaving out the k < 0 guard
def at_most(k):
left = total = count = 0def at_most(k):
if k < 0:
return 0
left = total = count = 0When 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
while total > goal:
total -= nums[left]
left += 1
if total == goal:
count += 1return 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
seen[prefix] += 1 answer += seen[prefix - goal]
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.
Edge cases
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.
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.
Complexity
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.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.