Video in progress
If an array gets many "sum from i to j" queries, how do you answer each in O(1)?
I build a prefix sum array once: pre[i] is the sum of the first i elements. Then the sum of the range [i, j] is pre[j + 1] - pre[i]. Building is O(n), each query is O(1).
📖 Answer
class RangeSum {
private final long[] pre;
RangeSum(int[] a) {
pre = new long[a.length + 1];
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
}
long sum(int from, int to) { // both bounds are inclusive
return pre[to + 1] - pre[from];
}
}
Making the array length n + 1 is deliberate: because pre[0] = 0, you don't need a separate if for ranges that start at the beginning. This cuts down off-by-one errors.
Where it's useful: queries like "revenue from March 1 to March 15" on a report page, and in the 2D variant, rectangle sums on an image or a map.
Prefix sum also solves another well-known problem: "the number of subarrays whose sum equals k". You need pre[j] - pre[i] = k, so for each j you look up in a HashMap how many times pre[j] - k has occurred. This works even with negative numbers, while a sliding window doesn't.
The limit: if the array keeps changing, rebuilding the prefix on each change is O(n). In that case you need a Fenwick tree or a segment tree.
Sign up to mark studied questions and save your progress.