Skip to content
DSA Patterns
Menu
Language
Prefix SumLC #5603 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.

Subarray Sum Equals K

Problem (restated)

Given an array of integers and an integer k, return the total number of continuous subarrays whose sum equals k.

Intuition

Prefix sums: count how often (pref - k) has occurred. Each such earlier prefix forms a valid subarray ending here.

Approaches

Prefix sum + hash map

Unverified
Time O(n)Space O(n)

Idea. count[0]=1. Walk array updating pref; ans += count[pref-k]; count[pref]++.

Walkthrough. nums=[1,1,1], k=2 → subarrays [1,1] twice → answer 2.

Trade-offs. Handles negatives (sliding window does not). Must seed count[0]=1.

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

Template connection

Map each prefix sum to how many times it has occurred, and seed 0 with 1. At prefix p, add the count of p - k, then record p. That count is the number of subarrays ending here that sum to k.

Reflection

  • count[pref - k] is how many earlier prefixes make this difference. Why seed count[0] = 1?
  • Negatives break a sliding window. Why does the hash map still work?
  • k = 0 and the array is all zeros: how many subarrays qualify?
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

Subarray sum equals k=2 on [1,1,1]. Count prefixes whose complement pref−k was seen.

1
0
1
1
1
2
map0→1

k = 2

Key:CurrentActive rangeMatchSettled