Skip to content

Start typing to search patterns, problems and pages.

Prefix Sum

Think of a car’s trip meter. To know how far you drove between two towns, you subtract the two readings. A prefix sum writes down the reading after every number, so the total of any stretch is one subtraction.

⏱ about 15 minutesNeeds: arrays, hash mapsTime O(n)Space O(n)

2 · Watch

Prefix Sum in 60 seconds

Here are 8 numbers. How many subarrays, runs of neighbours, add up to 7? Adding up every run one by one takes 36 sums.

3 · Now you drive

Keys:←→ stepSpace playR resetHomeEnd jump

Subarray Sum Equals K

or try
1–10 numbers from -9 to 9, then | and k from -30 to 30.
Count subarrays that add up to 7. The map starts with 0 once, for the empty prefix.Step 1 of 18. Counting subarrays of [3, 4, 7, 2, -3, 1, 4, 2] that sum to 7.
Step 1 of 18
solution.ts
function subarraySum(nums: number[], k: number): number {
const seen = new Map<number, number>([[0, 1]]); // prefix sum → times seen
let prefix = 0, count = 0;
for (const x of nums) {
prefix += x;
// A subarray ending here sums to k once for each earlier prefix of prefix - k.
count += seen.get(prefix - k) ?? 0;
seen.set(prefix, (seen.get(prefix) ?? 0) + 1);
}
return count;
}
▶ marks the line running now

4 · Your turn

0 of 5 problems solved

Start from this

// How many times each running total has shown up. The empty prefix is 0.
const seen = new Map<number, number>([[0, 1]]);
let prefix = 0;
let answer = 0;
for (const x of nums) {
  prefix += x;
  // A run ending here is good when an earlier total was prefix - k.
  answer += seen.get(prefix - k) ?? 0;
  // Store the total only after the lookup, so a run is never empty.
  seen.set(prefix, (seen.get(prefix) ?? 0) + 1);
}
return answer;

Easy ways to go wrong

  • Forgetting to seed the map with 0, which misses every run that starts at index 0.
  • Storing the total before the lookup, which counts an empty run when k is 0.
  • Using a sliding window when the numbers can be negative. The window sum no longer grows as it widens.
  • Taking a remainder of a negative total in JavaScript, which stays negative. Add k and take it again.
  1. Easy01

    Range Sum Query - Immutable

    LeetCode 303

    Store the running totals once. Each question is then one subtraction.

  2. Medium02

    Subarray Sum Equals K

    LeetCode 560

    The one you just watched. Write it from memory.

    Watch it run
  3. Medium03

    Contiguous Array

    LeetCode 525

    Count each 0 as -1, so a balanced run sums to 0. Keep the first index of each total.

  4. Medium04

    Continuous Subarray Sum

    LeetCode 523

    Store each total’s remainder mod k with the first index it showed up at.

  5. Medium05

    Subarray Sums Divisible by K

    LeetCode 974

    Count remainders instead of totals, and turn negative remainders positive.

UP NEXT · LESSON 5 OF 20StackRemember the past, answer on the way back.