Skip to main content
Intermediate ~10 min read

Prefix Sums

Precompute running totals once, then answer any range-sum query in O(1), the precomputation trade-off in its purest form.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Big O Notation & Time Complexity

A prefix sum array stores the running total of another array. Where the original array says "what is my value at index i?", the prefix array says "what is the total of everything before index i?" Building it takes one linear pass: prefix[i] = prefix[i-1] + arr[i-1]. Nothing clever, and that is the point. It is the simplest possible example of a hugely important trade-off: spend O(n) and O(n) memory once, and every future question gets cheaper.

The magic trick is the range query. The sum of arr[l..r] equals prefix[r+1] - prefix[l]. Both endpoints are a single O(1) lookup, so any range sum, any of the possibly thousands you need, costs the same two reads. Compare that to summing the range by hand every time: O(r - l) per query, which is O(n) at worst. With q queries, hand-summing is O(n·q); prefix sums make it O(n + q).

Build once, query forever

prefix-sums.js
// arr = [3, 1, 4, 1, 5]  →  prefix = [0, 3, 4, 8, 9, 14]
function buildPrefix(arr) {
  const prefix = new Array(arr.length + 1).fill(0);
  for (let i = 0; i < arr.length; i++) {
    prefix[i + 1] = prefix[i] + arr[i];   // running total, O(n)
  }
  return prefix;
}

// sum of arr[l..r] inclusive, two lookups, O(1)
function rangeSum(prefix, l, r) {
  return prefix[r + 1] - prefix[l];
}

const arr = [3, 1, 4, 1, 5];
const prefix = buildPrefix(arr);
rangeSum(prefix, 1, 3); // 1 + 4 + 1 = 6
rangeSum(prefix, 0, 4); // 14, the whole array

Why the padded 0 matters

  1. 1

    Start with prefix[0] = 0

    The extra leading zero means "sum of zero elements". It makes rangeSum work without special-casing l = 0, the formula prefix[r+1] - prefix[l] is true for every valid range.

  2. 2

    Watch the off-by-one direction

    prefix has length n + 1 while arr has length n. prefix[i] holds the sum of arr[0..i-1]. Mixing up this convention is the classic prefix-sum bug, pick one convention and never deviate.

  3. 3

    Reuse for other accumulations

    The same skeleton works for products, counts (prefix counts of "how many items match a predicate"), XORs, and minimums-with-caveats. Anything associative can ride the prefix pattern.

Cost summary

Operation / caseCostNotes
Build prefix arrayO(n)one pass, one extra array
Range sum queryO(1)two lookups + subtraction
Update an element, then queryO(n) rebuildprefix sums suit static data; frequent updates want a Binary Indexed Tree / segment tree

The classic interview follow-up: what if the array changes between queries? Prefix sums degrade, mention Fenwick trees to show you know the boundary of the technique.

Practice

arr = [2, 4, 6, 8]. What does rangeSum(prefix, 1, 2) return, and what two prefix values are subtracted?

Reveal explanation

prefix[3] - prefix[1] = 12 - 2 = 10, which is 4 + 6. The subtraction removes the accumulated total before index 1.

Check your understanding

  1. 1.What is the total cost of answering q range-sum queries on a static n-element array with prefix sums?
  2. 2.Why does the prefix array have length n + 1 instead of n?
  3. 3.The array receives 10,000 interleaved updates and queries. Best response?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going