Prefix Sums Answer Range Queries Fast

Build one running-total pass and a prefix array, then any i..j range sum is a single subtraction instead of another loop over the data.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
const dailyCents = [1200, 850, 430, 2750, 190];

// Running total: one pass, each checkpoint carries everything seen so far
let running = 0;
const checkpoints = dailyCents.map((cents) => {
  running += cents;
  return running;
});
console.log('checkpoints:', checkpoints.join(', '));

// Prefix array starts at 0 so subtraction covers the first element too
const prefix = [0];
for (const cents of dailyCents) {
  prefix.push(prefix[prefix.length - 1] + cents);
}

const rangeSum = (from, to) => prefix[to + 1] - prefix[from];
console.log('days 1-3:', rangeSum(1, 3));
console.log('full week:', rangeSum(0, dailyCents.length - 1));

const total = prefix[prefix.length - 1];
console.log('share by day 4:', Math.round((rangeSum(0, 3) / total) * 100) + '%');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

checkpoints: 1200, 2050, 2480, 5230, 5420
days 1-3: 4030
full week: 5420
share by day 4: 96%

The flow of the file

Everything happens inside the function rangeSum.

Iteration happens inside for (const cents of dailyCents) — everything outside it runs once.

What to watch for

  • No third-party code is loaded at any point while this runs.

Applying it

The method shape you reuse: const rangeSum = (from, to)

The run prints checkpoints:, days 1-3:, full week: — each prefix names the step that produced it.

Statements that matter

const rangeSum = (from, to) => prefix[to + 1] - prefix[from];
const checkpoints = dailyCents.map((cents) => {
  running += cents;
  return running;
});

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `rangeSum` at load time.