Keep Running Totals You Can Reuse

Picture a dashboard that shows daily page views, and a product manager who keeps asking for totals: views from day 3 through day 9, then day 10 through day 40, then the first week of each month. Adding up the requested days every time works, but each answer costs as much as the range is long. With thousands of questions over a long history, that adds up to O(n·q) work.

A prefix sum array does the adding once and then answers every range question with a single subtraction.

Build the Running Totals Once

Store at position i the total of everything before position i. Starting with a 0 makes the math line up, because the total of nothing is zero:

Language: JavaScript
const views = [120, 80, 200, 50, 90];
const prefix = [0];
for (const count of views) {
  prefix.push(prefix.at(-1) + count);
}
console.log(prefix);

The array is one item longer than the input, and its last entry is the grand total:

Language: Program Output
[ 0, 120, 200, 400, 450, 540 ]

Building it is one O(n) pass. From then on, the total of views[from] through views[to] is prefix[to + 1] - prefix[from], which is everything up to and including to, minus everything before from. Here’s that formula answering three questions:

Language: JavaScript
const views = [120, 80, 200, 50, 90];
const prefix = [0];
for (const count of views) prefix.push(prefix.at(-1) + count);

const rangeTotal = (from, to) => prefix[to + 1] - prefix[from];
console.log(rangeTotal(1, 3), rangeTotal(0, 4), rangeTotal(2, 2));

Each answer takes O(1) time, no matter how wide the range is:

Language: Program Output
330 540 200

The leading 0 is what makes a range that starts at day 0 work without a special case. Off-by-one slips around to + 1 are the most common bug in this pattern, so say out loud which positions are inclusive before you write the formula.

Pair Prefix Sums With a Map

Some questions turn the formula around. Instead of asking for the total of a given range, they ask which ranges have a given total. A stretch ending at position j totals target exactly when some earlier prefix sum equals prefix[j + 1] - target. That’s a lookup question, so a Map from each prefix sum to how often it has appeared, or to where it first appeared, answers it in O(1) on average.

This trick keeps working when values can be negative, such as refunds or lost followers. A sliding window can’t handle those, because adding an item no longer always moves the total in the same direction.

JavaScript Details That Interviewers Notice

Number has a safe integer limit. JavaScript numbers are 64-bit floats, so whole numbers are exact only up to Number.MAX_SAFE_INTEGER:

Language: JavaScript
> Number.MAX_SAFE_INTEGER
9007199254740991
> 9007199254740991 + 2
9007199254740992

Running totals grow faster than the values themselves, so mention this limit when the inputs can be huge. If totals might pass it, BigInt keeps them exact, at some cost in speed.

Floating-point totals drift. Adding decimal amounts collects tiny rounding errors, and subtracting two large prefix sums can expose them:

Language: JavaScript
> 0.1 + 0.2 + 0.3
0.6000000000000001
> 0.1 + 0.2 + 0.3 === 0.6
false

Keep money in whole cents, or any other integer unit, and both the totals and the === comparisons stay exact.

reduce() needs a starting value. values.reduce((sum, v) => sum + v) throws a TypeError on an empty array, so pass 0 as the second argument whenever the input can be empty.

In this section, you’ll answer batches of range questions, find a balance point, count stretches with an exact total, and review an AI-written budget checker that trips over floating-point money.

Become a Member to join the conversation.