Answer interval sums with prefix sums
Quick answer
A prefix sum stores cumulative totals. Build an array with an initial zero so any half-open interval sum can be found using one subtraction.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const values=[3,-2,5,1];const p=[0];for(const x of values)p.push(p[p.length-1]+x);console.log(JSON.stringify(p));Expected console output:
[0,3,1,6,7]Each prefix is the sum before that boundary.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
const p=[0,3,1,6,7];const range=(l,r)=>p[r]-p[l];console.log(range(0,4),range(1,3),range(2,2));Expected console output:
7 3 0Subtract the totals before the two boundaries.
How it works and cost model
Define prefix[0] = 0 and prefix[i+1] = prefix[i] + values[i]. For indices 0 <= l <= r <= n, sum([l,r)) = prefix[r] - prefix[l]. Construction is O(n) time and storage, each range query O(1) under a bounded arithmetic and random-access model. Empty intervals yield zero. Negative values work; prefix need not be increasing. A point update may require rebuilding later prefixes, so this is best for mostly read-only data.
Common mistakes
Keep the index convention explicit. Do not use prefix[r-1] with a half-open query or forget to rebuild after source mutation.
Practice
Build prefixes for [3,-2,5,1]. Answer [0,4), [1,3) and [2,2) without rescanning the input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Answer interval sums with prefix sums — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
Why store a leading zero in the prefix array?
What does prefix[r] - prefix[l] represent with the stated convention?
What trade-off is made by precomputing prefix sums for many interval queries?
What is the exact console output in the Prefix-sum range queries example 1?
const values=[3,-2,5,1];const p=[0];for(const x of values)p.push(p[p.length-1]+x);console.log(JSON.stringify(p));What is the exact console output in the Prefix-sum range queries example 2?
const p=[0,3,1,6,7];const range=(l,r)=>p[r]-p[l];console.log(range(0,4),range(1,3),range(2,2));