Prefix Sums
A prefix-sum array stores the running total of a sequence. The sum of any slice a[l .. r] then becomes one subtraction: pref[r+1] - pref[l].
Detailed Explanation
pref[0] = 0 and pref[i+1] = pref[i] + a[i]. After an O(n) build, a range sum is O(1). Many queries on a static array make this worth the extra n + 1 integers. Two-dimensional versions exist for matrices: a rectangle sum is four lookups.
C details are width and overflow. If a[i] is int and n is large, pref should be long long (or int64_t). Wrapping prefix sums can still be used modularly if you meant wrap; they are a bug if you meant mathematics on int.
The same idea works for XOR (pref[r+1] ^ pref[l]), for counts of a predicate (store 1 when true), and for difference arrays. A difference array d[i] = a[i] - a[i-1] turns a range increment a[l..r] += v into d[l] += v; d[r+1] -= v, then one prefix pass materializes a. That is how you apply many range updates in O(n + q).
Prefix sums need a static array, or they need rebuilds. If you change a[i] often and query often, a Fenwick tree or a segment tree is the dynamic version. Those are still prefix ideas with extra structure.
Off-by-one lives in the extra cell. pref has length n+1 so that an empty prefix is 0 and a[0..r] is pref[r+1]. Using length n and a special case for l == 0 is how people forget the case.
Space is O(n). If you only need one range, just loop. The table pays for itself at a handful of queries.
Code Examples
#include <stdio.h>
#include <stdlib.h>
static long long *build(const int *a, size_t n)
{
long long *pref = malloc((n + 1) * sizeof *pref);
if (pref == NULL) {
return NULL;
}
pref[0] = 0;
for (size_t i = 0; i < n; i++) {
pref[i + 1] = pref[i] + a[i];
}
return pref;
}
static long long range(const long long *pref, size_t l, size_t r)
{
return pref[r + 1] - pref[l]; /* sum of a[l..r] inclusive */
}
int main(void)
{
int a[] = { 2, 3, 5, 7 };
long long *p = build(a, 4);
if (p == NULL) {
return 1;
}
printf("%lld\n", range(p, 1, 3)); /* prints: 15 (3+5+7) */
free(p);
return 0;
}#include <stdio.h>
/* Difference array: add 5 to a[1..3], then materialize. */
int main(void)
{
int a[5] = { 0 };
int d[6] = { 0 };
d[1] += 5;
d[4] -= 5;
for (int i = 0; i < 5; i++) {
if (i > 0) {
d[i] += d[i - 1];
}
a[i] = d[i];
printf("%d ", a[i]);
}
printf("\n"); /* prints: 0 5 5 5 0 */
return 0;
}Common Gotchas
`pref[r] - pref[l]` with a length-`n` table is off by one for inclusive `r`
use `n+1` cells and `pref[r+1] - pref[l]`.
`int` prefix sums overflow
accumulate in `long long` unless you documented wrap.
One query does not need a table
the linear scan is simpler and uses `O(1)` extra space.
Updating `a[i]` invalidates every `pref[j]` for `j > i`
rebuild or use a Fenwick tree.