Binary Subarrays With Sum

Pattern: Sliding window: variable size

medium

Subarrays with sum exactly goal equal those with sum at most goal minus those with sum at most goal - 1. Each "at most" count is one sliding window.

The problem

You are given an array of 0s and 1s and a number goal. Count the blocks of neighbouring elements whose sum is exactly goal. For example, [1, 0, 1, 0, 1] with goal = 2 has 4 such blocks, and [0, 0, 0, 0, 0] with goal = 0 has 15 (every block).

The function name numSubarraysWithSum matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • With a rule of "sum exactly goal", what goes wrong when you try to shrink a window? Think about zeros.
  • A rule of "sum at most goal" behaves better. Why?
  • How do you get "exactly" from two "at most" counts?

Hints

    Brute force, and why it fails

    Check every block with a running sum: O(n²). Two sliding windows make it O(n). Prefix sums with a hash map also give O(n), with O(n) memory.

    The key insight

    "At most" rules shrink cleanly, and "exactly" is the difference of two "at most" counts. The same trick works for any count that only grows as the window grows.

    Dry run

    10 
    01 
    12 
    03 
    14 
    goal2

    nums = [1, 0, 1, 0, 1] and goal = 2. First count windows with sum at most 2. For each right, the window from left to right is the longest allowed, and right - left + 1 subarrays end there.

    Step 1 of 4

    The plan

    function atMost(g):
        if g < 0: return 0
        left = 0, sum = 0, count = 0
        for right from 0 to n - 1:
            sum = sum + nums[right]
            while sum > g:
                sum = sum - nums[left]
                left = left + 1
            count = count + (right - left + 1)
        return count
    
    return atMost(goal) - atMost(goal - 1)
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two passes, each O(n), with a few counters.

    Edge cases

    • goal = 0: count blocks of zeros only. atMost(-1) must return 0.
    • goal above the number of ones: 0.
    • All zeros with goal = 0: every block, n(n + 1)/2.
    I've built my logic, show the code

    Java

    class Solution {
        public int numSubarraysWithSum(int[] nums, int goal) {
            return atMost(nums, goal) - atMost(nums, goal - 1);   // exactly goal = at most goal minus at most goal - 1
        }
    
        private int atMost(int[] nums, int goal) {
            if (goal < 0) return 0;
            int left = 0, sum = 0, count = 0;
            for (int right = 0; right < nums.length; right++) {
                sum += nums[right];
                while (sum > goal) {
                    sum -= nums[left];
                    left++;
                }
                count += right - left + 1;          // every subarray ending at right and starting in the window
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int numSubarraysWithSum(vector<int>& nums, int goal) {
            return atMost(nums, goal) - atMost(nums, goal - 1);   // exactly goal = at most goal minus at most goal - 1
        }
    
        int atMost(vector<int>& nums, int goal) {
            if (goal < 0) return 0;
            int left = 0, sum = 0, count = 0;
            for (int right = 0; right < static_cast<int>(nums.size()); right++) {
                sum += nums[right];
                while (sum > goal) {
                    sum -= nums[left];
                    left++;
                }
                count += right - left + 1;          // every subarray ending at right and starting in the window
            }
            return count;
        }
    };

    Python

    class Solution:
        def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:
            return self.at_most(nums, goal) - self.at_most(nums, goal - 1)   # exactly = at most goal minus at most goal - 1
    
        def at_most(self, nums: list[int], goal: int) -> int:
            if goal < 0:
                return 0
            left = total = count = 0
            for right, v in enumerate(nums):
                total += v
                while total > goal:
                    total -= nums[left]
                    left += 1
                count += right - left + 1           # every subarray ending at right and starting in the window
            return count

    Common mistakes

    • Trying one window with "sum == goal" and missing the blocks that differ only by leading zeros.
    • Forgetting the g < 0 guard, which makes the window loop misbehave for goal = 0.
    • Adding 1 per window instead of right - left + 1.

    Similar problems