Data Structures & Algorithms / Module 5: Algorithm patterns

Topic 5.3

Prefix sums

Running totals that turn any range sum into one subtraction.

8 min · intermediate

Watch: the front row keeps a running total. After that, the sum of any range takes just one subtraction.

0123456P[0]P31410592
  • moving now
  • being checked
  • passed / marked
  • finished / the result
Step 1 of 11

P[0] = 0: the sum of no numbers at all.

Build P once, in one pass. After that, the sum of any range is the difference of two entries in P.

Like a car's odometer

An odometer records total distance since the car was new. Want the distance from one town to the next? You don't add up every stretch of road. Just subtract the reading when you left from the reading when you arrived. A prefix sum is an odometer for an array.

Code, for programmersBuild once, answer many times
function buildPrefix(a) {
  const P = [0];                         // P[0] = sum of no numbers
  for (const x of a) P.push(P[P.length - 1] + x);
  return P;                              // P has a.length + 1 entries
}

// sum of a[from..to], both ends included
const rangeSum = (P, from, to) => P[to + 1] - P[from];

const P = buildPrefix([3, 1, 4, 1, 5, 9, 2]);
rangeSum(P, 2, 5);   // 4 + 1 + 5 + 9 = 19

When it pays off

If you only need one range sum, just add it up. Prefix sums pay off when there are many questions about data that doesn't change. With n values and q questions, adding directly can cost n × q steps. With a prefix sum: n to build, then 1 per question, n + q in total.

Where you meet it

  • Sales dashboards: "total revenue from 1 to 15 March" from a table of daily running totals.
  • Image processing: a summed-area table, a two-dimensional prefix sum, gives the average of any rectangle in one step (used for fast blurs).
  • Counting subarrays that sum to k: keep every prefix in a hash map and check whether P − k has appeared before.

Quiz

  1. P = [0, 3, 4, 8, 9, 14]. What is the sum of a[1] to a[3]?

  2. When does a prefix sum pay off most?

  3. Why does P start with 0?

0 of 3 answered.