Binary Subarrays With Sum (LeetCode 930): Solution and Explanation
Given a binary array and a target sum, count the non-empty contiguous subarrays whose elements add up to exactly that target.
Intuition
Fix the right end of a subarray and ask which left ends work. Moving the left end one step right can only keep the sum the same or drop it by one, because every value is 0 or 1.
So the sums of the subarrays ending at right, read from left to right, never go up. The starts that give exactly goal sit next to each other in one band.
Mark the band with two pointers. lo is the first start whose sum is at most goal; hi is the first start whose sum is below goal. Every start in [lo, hi) gives exactly goal, so hi - lo subarrays end at right.
When right moves forward the sums only grow, so both lo and hi only move forward too. That makes the whole scan linear.
Approach: Sliding window with two left pointers
- Set
lo = hi = 0, their running sumssumLo = sumHi = 0, andcount = 0. - For each
right, addnums[right]to both running sums. - While
lo <= rightandsumLo > goal, subtractnums[lo]fromsumLoand moveloright. - While
hi <= rightandsumHi >= goal, subtractnums[hi]fromsumHiand movehiright. - Add
hi - lotocount. After the loop, returncount.
Step-by-step example
nums = [1,0,1,0,1], goal = 2
- Right ends 0 and 1: the sum from index 0 is only 1, so no start reaches 2.
lo = hi = 0and nothing is added. - Right end 2: the sum from 0 is now 2.
himoves past index 0 and stops at 1, where the sum is 1. The band[0, 1)adds 1, so count = 1. - Right end 3: the new element is 0. The sum from 0 is still 2 and the sum from 1 is still 1, so the band stays
[0, 1)and count = 2. - Right end 4: the sum from 0 is 3, so
lomoves to 1 (sum 2).himoves past index 1 (sum 2) and index 2 (sum 2) and stops at 3 (sum 1). The band[1, 3)adds 2, giving the answer 4.
Code: Python, Java, C++
1class Solution:
2 def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
3 lo = hi = 0
4 sum_lo = sum_hi = 0
5 count = 0
6 for right in range(len(nums)):
7 sum_lo += nums[right]
8 sum_hi += nums[right]
9 while lo <= right and sum_lo > goal:
10 sum_lo -= nums[lo]
11 lo += 1
12 while hi <= right and sum_hi >= goal:
13 sum_hi -= nums[hi]
14 hi += 1
15 count += hi - lo
16 return count1class Solution {
2 public int numSubarraysWithSum(int[] nums, int goal) {
3 int lo = 0, hi = 0, sumLo = 0, sumHi = 0, count = 0;
4 for (int right = 0; right < nums.length; right++) {
5 sumLo += nums[right];
6 sumHi += nums[right];
7 while (lo <= right && sumLo > goal) {
8 sumLo -= nums[lo++];
9 }
10 while (hi <= right && sumHi >= goal) {
11 sumHi -= nums[hi++];
12 }
13 count += hi - lo;
14 }
15 return count;
16 }
17}1class Solution {
2public:
3 int numSubarraysWithSum(vector<int>& nums, int goal) {
4 int lo = 0, hi = 0, sumLo = 0, sumHi = 0, count = 0;
5 for (int right = 0; right < (int)nums.size(); right++) {
6 sumLo += nums[right];
7 sumHi += nums[right];
8 while (lo <= right && sumLo > goal) {
9 sumLo -= nums[lo++];
10 }
11 while (hi <= right && sumHi >= goal) {
12 sumHi -= nums[hi++];
13 }
14 count += hi - lo;
15 }
16 return count;
17 }
18};Time and space complexity
O(n)
right visits each index once, and lo and hi each move forward at most n times in total.
O(1)
Only three pointers, two running sums and the count are stored.
Other approaches
Prefix sums with a hash map (time O(n), space O(n))
Walk the array keeping a running prefix sum and a map from prefix value to how many times it has appeared. At each index add seen[prefix - goal]. This is the same idea as Subarray Sum Equals K and works for any integers.
At most goal minus at most goal - 1 (time O(n), space O(1))
Write a helper that counts subarrays with sum at most g using one shrinking window, then return atMost(goal) - atMost(goal - 1). Return 0 for the helper when g < 0.
Check every subarray (time O(n^2), space O(1))
For each start, extend the end and keep a running sum, counting the times it equals goal. Simple but quadratic.
Common mistakes
- Using a single shrinking window. It finds one valid start per right end, but zeros at the front of the window create several valid starts that a single pointer skips.
- Forgetting the
hi <= rightguard. Withgoal = 0an empty window has sum 0, andhiwould run pastright. - Calling
atMost(goal - 1)withgoal = 0without handling the negative bound, which should return 0. - Typing expected answers for all-zero arrays by hand: with
goal = 0, n zeros give n(n+1)/2 subarrays.
Frequently asked questions
Why do the valid starts form one contiguous band?
Every value is 0 or 1, so as the start moves right the sum never increases. The starts with sum exactly goal therefore sit between the last start whose sum is too big and the first start whose sum is too small.
Does this work if the array can hold negative numbers?
No. Negative values break the monotonic sums that the window depends on. Use the prefix sum hash map instead, as in Subarray Sum Equals K.
Can the count overflow a 32-bit integer?
The largest count is n(n+1)/2 for n = 30,000, about 450 million, which still fits in a signed 32-bit integer.