Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Arrays & Windows

The Running Total.

Watch the explainer

Don't memorize prefix sums — watch the running total build. Add up the array once into a cumulative list where P[i] is the total of everything up to i. After that one O(n) pass, the sum of any range is a single subtraction — P[j] − P[i−1] — answered in O(1), no matter how many times you ask.

cumulative sum · range query · O(1) · preprocessing
PREFIX P[i]

The total of A[0..i] — everything up to and including index i.

BUILD

P[i] = P[i−1] + A[i], one pass, O(n).

RANGE SUM

sum(i..j) = P[j] − P[i−1]. One subtraction.

PAYOFF

m queries cost O(n + m), not O(n·m).

prefix-sums.sim — build, then range queries
Ready

Top row is the array A; bottom row is the prefix sums P. Press Step to build P cell by cell — each is the one before it plus the value above — then answer range-sum queries with a single subtraction.

P[i] = P[i−1] + A[i]
Build
Phase
O(n)
Cost

Precompute once, subtract forever

Summing a range the naive way re-adds every element each time you ask — fine for one query, terrible for thousands. Prefix sums pay the cost once: a single sweep builds a running total, and from then on the sum of any contiguous slice is the total up to the end of the slice minus the total just before it starts. Everything before the range cancels, leaving exactly the range.

01

Build the prefix array

P[0] = A[0], then P[i] = P[i−1] + A[i]. One O(n) pass, O(n) space.

02

Answer a range query

sum(i..j) = P[j] − P[i−1] (treat P[−1] as 0). One subtraction — O(1).

03

Why it works

P[j] counts everything through j; P[i−1] counts everything before i. Subtract and only the range i..j survives.

04

Extend it

2-D prefix sums (integral images) answer sub-rectangle sums with four lookups; a Fenwick tree adds O(log n) updates.

Build
O(n)
Range query
O(1)
m queries total
O(n + m)
Space
O(n)

The catch: prefix sums assume the array does not change. Update one value and every prefix after it is stale, costing O(n) to fix — which is exactly the gap a Fenwick (binary indexed) tree or a segment tree fills, trading O(1) queries for O(log n) queries and O(log n) updates.

The picture: one subtraction cancels the prefix

AP 0331142483194514592362257631 sum(2..5) = P[5] − P[1] = 23 − 4 = 19
The array [3, 1, 4, 1, 5, 9, 2, 6] and its prefix sums. To get the sum of indices 2 to 5, take P[5] (everything up to index 5, highlighted) and remove P[1] (everything before index 2, marked in the bottom row). What is left is exactly the highlighted range in the top row: 19.

Worked example, step by step

Take A = [3, 1, 4, 1, 5, 9, 2, 6]. One pass builds P = [3, 4, 8, 9, 14, 23, 25, 31], using 7 additions. Then answer seven range queries, each with a single subtraction. When the range starts at 0 there is nothing to remove, so the subtracted term is 0.

Query l..rP[r]P[l−1]SubtractionSumElements a rescan reads
0..280 (empty)8 − 083
2..523423 − 4194
3..3989 − 811
0..7310 (empty)31 − 0318
4..731931 − 9224
1..625325 − 3226
5..5231423 − 1491

The last column is what the trace is for. The seven queries cost seven subtractions after the build; re-adding the ranges would read 27 array elements, and that gap grows with every extra query and every longer range. Query 0..7 costs the same single subtraction as 5..5: range length stops mattering. The case l = 0 is the only special one, since there is no P[−1]. Many implementations avoid the branch by storing a leading zero so that pre[i] is the sum of the first i elements and every range sum is pre[r+1] − pre[l].

The same idea in two dimensions. Take a 3 × 3 grid with rows [3, 1, 4], [1, 5, 9] and [2, 6, 5]. Build a table S with a leading row and column of zeros, where S[i][j] is the sum of every cell above and to the left of row i, column j. Its last row is [0, 6, 18, 36], and 36 is the whole grid. To sum the bottom-right 2 × 2 block (5, 9, 6, 5), take the big corner, remove the strip above and the strip to the left, then add back the corner you removed twice: 36 − 8 − 6 + 3 = 25. Check: 5 + 9 + 6 + 5 = 25. That is four lookups, whatever the size of the rectangle. Forgetting the + 3 is the classic bug, and it returns 22.

Complexity and trade-offs

CaseTimeSpaceWhy
Prefix sumsbuild O(n), query O(1), update O(n)O(n)One sweep, then each query is one subtraction. A changed value makes every later prefix stale.
Re-sum each queryO(1) prep, query O(n)O(1)m queries cost O(n·m). Fine for a handful, wrong for thousands.
Fenwick treebuild O(n), query and update O(log n)O(n)Keeps partial sums by power-of-two blocks. Use it when the array changes between queries.
Segment treebuild O(n), query and update O(log n)O(n)Same bounds, and it also handles min, max and gcd, which have no subtraction to undo a prefix.
Difference arrayrange add O(1), rebuild O(n)O(n)The inverse tool: many range additions, then one pass of prefix sums to read the final values.

Prefix sums need an operation with an inverse. Addition has subtraction, so P[j] − P[i−1] works. max has no inverse: knowing the maximum of the first 6 elements and of the first 2 does not give the maximum of elements 2 to 5. For those, use a segment tree or a sparse table. With no updates, a prefix array is the smallest, fastest structure for sums, counts and XOR.

Common mistakes

  • Reading P[l−1] when l is 0

    With the inclusive layout above, query 0..2 needs P[−1]. In Python, P[-1] is the last element and does not raise: P[2] − P[-1] gives 8 − 31 = −23 instead of 8. In C or Java it reads out of bounds. Use a leading zero, or branch on l == 0.

  • Letting the sum overflow a 32-bit int

    A prefix of 105 values each up to 105 reaches 1010, but a signed 32-bit int tops out at 2,147,483,647. The prefix wraps negative and later subtractions look plausible but are wrong. Store P as a 64-bit integer.

  • Querying after the array changed

    Set A[2] = 10 (up by 6) without rebuilding P. The query 2..5 still returns 19, but the true sum is 25. Nothing crashes. If updates are interleaved with queries, rebuild, or switch to a Fenwick tree.

  • Forgetting the empty prefix in the hash-map variant

    Counting subarrays with sum k stores earlier prefix sums in a map. For [1, 2, 3] with k = 3 the answer is 2 ([1, 2] and [3]). Without seeding the map with {0: 1} it finds only 1, because [1, 2] starts at index 0 and needs the empty prefix.

  • Off-by-one between inclusive and exclusive ends

    Mixing the two layouts is the usual source of answers that are off by exactly one element. Pick one (pre[r+1] − pre[l] for inclusive [l, r]) and write it once, in a helper.

Where this shows up

  • Integral images in computer vision

    A 2-D prefix sum, called a summed-area table or integral image, gives the sum over any rectangle of pixels with four lookups. The Viola–Jones face detector relies on it to evaluate thousands of rectangle features per window cheaply.

  • SQL running totals

    SUM(amount) OVER (ORDER BY day) is a prefix sum computed by the database. A range total between two dates is the difference of two running totals.

  • Counting sort and radix sort

    Counting sort turns per-value counts into starting positions with a prefix sum, so each element lands in its final slot in one more pass.

  • Parallel scans

    GPU libraries ship a parallel prefix scan (the Blelloch scan is the standard design). It is a building block for stream compaction, histograms and radix sort, which is why the sequential idea here matters beyond arrays.

SOLVE IT YOURSELF

Solve it: range sums in O(1)

This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement range_sum(nums, queries): precompute a prefix-sum array once, then answer each query [l, r] with the inclusive sum of nums[l..r] in O(1). Return the list of answers. Building the prefix array is O(n); each query is then a single subtraction.

HINTS — 4 IDEAS
  1. Build pre where pre[i] = sum of the first i elements, with pre[0] = 0.
  2. Then pre[i+1] = pre[i] + nums[i] — one pass, O(n).
  3. The inclusive sum of nums[l..r] is pre[r+1] − pre[l].
  4. Map every query through that formula — each is O(1), no re-scanning.
CPython · WebAssembly

Check yourself

1 · How is the prefix array built?

Each prefix is the previous running total plus the current value — a single cumulative pass.

2 · What is the sum of the range i..j using prefix sums?

Total up to j minus total before i leaves exactly the range i..j — one subtraction, O(1).

3 · When do prefix sums stop being ideal?

An update invalidates every later prefix (O(n) to rebuild); a Fenwick or segment tree handles updates in O(log n).

Questions

Why keep P[i−1] instead of just P[i]?

Because a range starting at i needs everything before i removed. P[i−1] is precisely that total, so subtracting it strips off the prefix and leaves the range. Using an extra leading zero (P of length n+1) is a common trick to avoid the i=0 special case.

What problems use prefix sums?

Range-sum queries, subarray-sum-equals-k (with a hash map of prefix counts), equilibrium and pivot indices, running averages, and — in 2-D — image box filters and sub-rectangle sums.

How does subarray-sum-equals-k use them?

As you scan, keep a hash map of how many times each prefix sum has occurred. At index j, the number of subarrays ending at j with sum k is the count of prefix sum P[j] − k seen so far — turning an O(n²) search into O(n).

One pass up front, O(1) forever after.

Build the running total once, then every range is a subtraction. Preprocessing that pays for itself.

▶  Watch it explained

Prefix Sums: Answer Any Range in ONE Subtraction

Finished this one? 0 / 99 Algorithms done
NextThe Waiting Line: Monotonic Stack Next on the “Two pointers and a window” ladder · rung 5 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms