Prefix Sum

Precompute running totals to answer any range-sum in O(1) — and combine with a hash map to count subarrays in O(n).

Beginner 2 min readLesson 5 of 25

A prefix sum array stores running totals: P[i] = sum of the first i elements. Then the sum of any range is a single subtraction:

sum(a[l..r])=P[r+1]−P[l]\text{sum}(a[l..r]) = P[r+1] - P[l]
0123456aP314159–034891423
P has a leading 0. sum(a[2..4]) = P[5] − P[2] = 14 − 4 = 10.
When to use this pattern
  • Many range-sum queries on an array that doesn't change.
  • "Count / find subarrays whose sum (or xor, or count of something) equals k" — especially with negative numbers, where sliding window fails.
  • Balance problems: equal numbers of 0s and 1s, equal counts of two characters (map 0 → −1).
  • 2D grid region sums.
  • Many range updates followed by reads → the inverse trick, a difference array.

Range sum queries

class RangeSum {
    private final long[] p;
    RangeSum(int[] a) {
        p = new long[a.length + 1];
        for (int i = 0; i < a.length; i++) p[i + 1] = p[i] + a[i];
    }
    long sum(int l, int r) { return p[r + 1] - p[l]; }   // inclusive l..r
}

Prefix sum + hash map: subarray sum equals k

A subarray (j, i] sums to k exactly when P[i] − P[j] = k, i.e. when an earlier prefix equals P[i] − k. So scan once, keeping a count of prefix sums seen so far.

int subarraySum(int[] a, int k) {
    Map<Integer, Integer> seen = new HashMap<>();
    seen.put(0, 1);                       // empty prefix
    int sum = 0, count = 0;
    for (int x : a) {
        sum += x;
        count += seen.getOrDefault(sum - k, 0);
        seen.merge(sum, 1, Integer::sum);
    }
    return count;
}

Variations: store the first index of each prefix to get the longest such subarray; store prefix sums mod k for "subarray sum divisible by k"; map 0 → −1 to find the longest subarray with equal 0s and 1s (prefix 0 repeats).

2D prefix sums

P[r][c] = sum of the rectangle from (0,0) to (r−1, c−1). Any sub-rectangle sum then needs four lookups (inclusion–exclusion):

S=P[r2+1][c2+1]−P[r1][c2+1]−P[r2+1][c1]+P[r1][c1]S = P[r_2+1][c_2+1] - P[r_1][c_2+1] - P[r_2+1][c_1] + P[r_1][c_1]
class Matrix2D {
    private final int[][] p;
    Matrix2D(int[][] m) {
        int R = m.length, C = m[0].length;
        p = new int[R + 1][C + 1];
        for (int r = 0; r < R; r++)
            for (int c = 0; c < C; c++)
                p[r + 1][c + 1] = m[r][c] + p[r][c + 1] + p[r + 1][c] - p[r][c];
    }
    int sum(int r1, int c1, int r2, int c2) {
        return p[r2 + 1][c2 + 1] - p[r1][c2 + 1] - p[r2 + 1][c1] + p[r1][c1];
    }
}

Difference arrays: O(1) range updates

To add v to every element in [l, r] many times, record d[l] += v and d[r + 1] -= v. After all updates, the prefix sum of d gives the final array. Used for "corporate flight bookings", "car pooling", and counting overlapping intervals at each point.

Practice problems
  • Range Sum Query – Immutableeasy
  • Running Sum of 1d Arrayeasy
  • Find Pivot Indexleft sum == total − left − a[i]easy
  • Subarray Sum Equals Kcount of prefix − kmedium
  • Continuous Subarray Sumprefix mod k, first indexmedium
  • Subarray Sums Divisible by Kmedium
  • Contiguous Array0 → −1, longest zero-summedium
  • Product of Array Except Selfprefix × suffixmedium
  • Range Sum Query 2D – Immutablemedium
  • Car Poolingdifference arraymedium
Key takeaways
  • P[i+1] = P[i] + a[i]; range sum = P[r+1] − P[l] in O(1).
  • Prefix sum + hash map counts subarrays with a target sum in O(n), negatives included.
  • 2D prefix sums answer rectangle sums with inclusion–exclusion.
  • Difference arrays turn range updates into O(1) operations.