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).
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:
- 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
}from itertools import accumulate
class RangeSum:
def __init__(self, a):
self.p = [0, *accumulate(a)]
def sum(self, l, r): # inclusive l..r
return self.p[r + 1] - self.p[l]class RangeSum {
private p: number[];
constructor(a: number[]) {
this.p = [0];
for (const x of a) this.p.push(this.p[this.p.length - 1] + x);
}
sum(l: number, r: number) { return this.p[r + 1] - this.p[l]; }
}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;
}from collections import defaultdict
def subarray_sum(a, k):
seen = defaultdict(int, {0: 1}) # empty prefix
total = count = 0
for x in a:
total += x
count += seen[total - k]
seen[total] += 1
return countfunction subarraySum(a: number[], k: number): number {
const seen = new Map<number, number>([[0, 1]]);
let sum = 0, count = 0;
for (const x of a) {
sum += x;
count += seen.get(sum - k) ?? 0;
seen.set(sum, (seen.get(sum) ?? 0) + 1);
}
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):
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];
}
}class Matrix2D:
def __init__(self, m):
R, C = len(m), len(m[0])
self.p = [[0] * (C + 1) for _ in range(R + 1)]
for r in range(R):
for c in range(C):
self.p[r + 1][c + 1] = m[r][c] + self.p[r][c + 1] + self.p[r + 1][c] - self.p[r][c]
def sum(self, r1, c1, r2, c2):
p = self.p
return p[r2 + 1][c2 + 1] - p[r1][c2 + 1] - p[r2 + 1][c1] + p[r1][c1]class Matrix2D {
private p: number[][];
constructor(m: number[][]) {
const R = m.length, C = m[0].length;
this.p = Array.from({ length: R + 1 }, () => new Array(C + 1).fill(0));
for (let r = 0; r < R; r++)
for (let c = 0; c < C; c++)
this.p[r + 1][c + 1] = m[r][c] + this.p[r][c + 1] + this.p[r + 1][c] - this.p[r][c];
}
sum(r1: number, c1: number, r2: number, c2: number) {
const p = this.p;
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.
- 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
- 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.