Skip to content
DSA Patterns
Menu
Language
Prefix SumLC #9305 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Binary Subarrays With Sum

Problem (restated)

Given a binary array and goal, return the number of non-empty subarrays with sum == goal.

Intuition

Classic prefix-count: for each prefix S, add count of prefixes equal to S-goal.

Approaches

Prefix sum hash

Unverified
Time O(n)Space O(n)

Idea. Map prefix→count; initialize prefix 0 with count 1; accumulate answers.

Walkthrough. [1,0,1,0,1], goal=2 → 4 subarrays.

Trade-offs. Sliding window atMost(goal)-atMost(goal-1) also works for binary arrays.

Solution
export function numSubarraysWithSum(nums: number[], goal: number): number {
  const map = new Map<number, number>([[0, 1]]);
  let sum = 0, ans = 0;
  for (const x of nums) {
    sum += x;
    ans += map.get(sum - goal) ?? 0;
    map.set(sum, (map.get(sum) ?? 0) + 1);
  }
  return ans;
}
export function numSubarraysWithSum(nums: number[], goal: number): number {
  const map = new Map<number, number>([[0, 1]]);
  let sum = 0, ans = 0;
  for (const x of nums) {
    sum += x;
    ans += map.get(sum - goal) ?? 0;
    map.set(sum, (map.get(sum) ?? 0) + 1);
  }
  return ans;
}

Template connection

Prefix hash: seed 0 with count 1. At prefix p, add the count of p - goal, then record p. The window form atMost(goal) - atMost(goal - 1) is the same count and keeps only a few integers.

Reflection

  • Count prefixes. How many earlier prefixes equal pref - goal? Seed prefix 0 with count 1.
  • On a binary array, atMost(goal) - atMost(goal - 1) is the other O(n) form. Why is that window O(1) memory while the hash is not?
  • goal = 0 counts only the runs of zeros.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Count binary subarrays with sum = 2. Prefix + map of seen sums.

1
0
0
1
1
2
0
3
1
4
map0→1

goal = 2

Key:CurrentActive rangeMatchSettled