Skip to main content

Prefix Sum

Allows O(1)O(1) range sum queries after O(n)O(n) preprocessing.
// 1-based indexing is often easier
for (int i = 1; i <= n; i++) {
    pref[i] = pref[i-1] + a[i];
}

// Sum of range [L, R]
long long sum = pref[R] - pref[L-1];

2D Prefix Sum

Sum of a rectangle from (x1,y1)(x1, y1) to (x2,y2)(x2, y2).
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
        pref[i][j] = a[i][j] + pref[i-1][j] + pref[i][j-1] - pref[i-1][j-1];
    }
}

// Query
long long sum = pref[x2][y2] - pref[x1-1][y2] - pref[x2][y1-1] + pref[x1-1][y1-1];

Difference Array

Used for range updates (add VV to [L,R][L, R]) in O(1)O(1). After all updates, calculate prefix sums to get the final values.
diff[L] += V;
diff[R+1] -= V;

// Recover original array
for (int i = 1; i <= n; i++) {
    val[i] = val[i-1] + diff[i];
}

Practice

Sheet 7: Static Range Queries

Practice problems for this tutorial.