Arrays & Hashing · Pattern 10 of 26

Prefix sums

prefix[i] = sum of the first i values, so any subarray sum is a difference of two prefixes. With a hash map of earlier prefixes you can count subarrays with an exact sum, remainder or XOR in one pass.

5 variations · 17 problems · 9 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Many range-sum queries on a fixed array
  • Count subarrays whose sum equals k or is divisible by k
  • Negative numbers present (a sliding window will not work)
  • Balance problems: equal 0s and 1s, equal vowels

The template

Prefix Sum Strategy
int subarraySum(int[] nums, int k) {           // subarrays with sum exactly k
    Map<Integer, Integer> seen = new HashMap<>();   // prefix sum -> how many times
    seen.put(0, 1);                                 // the empty prefix
    int sum = 0, count = 0;
    for (int x : nums) {
        sum += x;
        count += seen.getOrDefault(sum - k, 0);     // earlier prefixes that leave exactly k
        seen.merge(sum, 1, Integer::sum);
    }
    return count;
}

The variations

  1. 1Range sums from a prefix array

    Build prefix once, then sum(l..r) = prefix[r + 1] − prefix[l] in O(1). Pivot index, minimum start value, candles between plates and shop penalty all read prefixes.

  2. 2Count subarrays with a sum

    Look up sum − k among earlier prefixes. For "equal 0s and 1s", count 0 as −1 and look for equal prefixes.

  3. 3Remainders mod k

    Two prefixes with the same remainder enclose a subarray divisible by k. Store the remainder instead of the sum.

  4. 4Prefix XOR and bitmasks

    XOR works like a sum: xor(l..r) = prefix[r + 1] ^ prefix[l]. A bitmask of odd/even letter counts is a prefix XOR too.

  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Forgetting the empty prefix (0 → 1), which misses subarrays that start at index 0.
  • Updating the map before checking it, which counts the empty subarray when k = 0.
  • Negative remainders in Java, C++ and JS: use ((sum % k) + k) % k.
Next: Sliding window of a fixed size →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.