All algorithms
Data Structures

Prefix Sums

Precompute once, then answer any range sum with a single subtraction.

TimeO(n) build, O(1) querySpaceO(n)CategoryData Structures

A prefix sum array stores the total of everything up to each index. Once built, the sum of any range [l, r] is `pref[r+1] - pref[l]` — one subtraction, no loop, no matter how wide the range.

It turns 'many range-sum queries' from O(n) each into O(1) each, and the same idea extends to 2D grids and to difference arrays for range updates. When the array also changes between queries you need a Fenwick or segment tree instead.

The off-by-one in the indexing is where everyone stumbles. AlgoLens shows `pref` alongside the original array, which makes the shift obvious rather than something to memorise.

The code

prefix_sums.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {3, 1, 4, 1, 5, 9};
    int n = a.size();

    vector<int> pref(n + 1, 0);
    for (int i = 0; i < n; i++) pref[i + 1] = pref[i] + a[i];

    // The sum of range [l, r] is a single subtraction.
    int l = 1, r = 4;
    cout << pref[r + 1] - pref[l] << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Prefix Sums

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going