C · Pupil · 14 min

Prefix Sums: Range Answers for Free

Spend O(n) once, then answer any contiguous sum (and many cousins) in O(1). This is the first real contest pattern.

A prefix sum array pref[i] stores the sum of the first i elements (or of a[0..i], depending on indexing). After you build it, the sum of any contiguous slice is a subtraction.

0-based, pref[-1] treated as 0:

sum(l, r) = pref[r] - pref[l - 1]

That identity is the whole trick. Everything else is bookkeeping.

Build once, query oftenjs
function buildPrefix(a) {
  const pref = new Array(a.length);
  let running = 0;
  for (let i = 0; i < a.length; i++) {
    running += a[i];
    pref[i] = running;
  }
  return pref;
}

function rangeSum(pref, l, r) {
  const left = l === 0 ? 0 : pref[l - 1];
  return pref[r] - left;
}

TRACE

Build the prefix of a = [2, 1, 3, 4] by hand.

i = 0

running = 2. pref = [2, _, _, _]

pref[0] = 2

1 / 5

CHECK

pref[i] = a[0] + … + a[i]. Which expression is the sum of a[2] + a[3] + a[4]?

Kadane's algorithm (maximum subarray) is a close cousin: instead of storing every prefix, you track the best prefix ending here, and reset when it goes negative. You will implement it in the arena as Maximum Subarray.

CHECK

You must answer 10⁵ range-sum queries on a static array of length 10⁵. Why not recompute each sum with a loop?

Checks 0/2

Next lesson