Skip to content
ΣDSA Patterns
Menu
Language

Prefix Sum

Guide 5 of 6 · Path 5 of 6

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
0
1
0
1
map0→1

goal = 2

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

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-sum hash (or atMost(goal) − atMost(goal-1)) for binary subarrays.

Reflection