Binary Subarrays With Sum (LeetCode 930): Solution and Explanation

Medium
Array
Hash Table
Sliding Window
Prefix Sum

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

  1. Set lo = hi = 0, their running sums sumLo = sumHi = 0, and count = 0.
  2. For each right, add nums[right] to both running sums.
  3. While lo <= right and sumLo > goal, subtract nums[lo] from sumLo and move lo right.
  4. While hi <= right and sumHi >= goal, subtract nums[hi] from sumHi and move hi right.
  5. Add hi - lo to count. After the loop, return count.

Step-by-step example

nums = [1,0,1,0,1], goal = 2
  1. Right ends 0 and 1: the sum from index 0 is only 1, so no start reaches 2. lo = hi = 0 and nothing is added.
  2. Right end 2: the sum from 0 is now 2. hi moves past index 0 and stops at 1, where the sum is 1. The band [0, 1) adds 1, so count = 1.
  3. 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.
  4. Right end 4: the sum from 0 is 3, so lo moves to 1 (sum 2). hi moves 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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

right visits each index once, and lo and hi each move forward at most n times in total.

Space

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 <= right guard. With goal = 0 an empty window has sum 0, and hi would run past right.
  • Calling atMost(goal - 1) with goal = 0 without 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.