Skip to content

Pattern · Interview prep

Prefix Sum

Keep a running total from the start of the row, so a later range is one subtraction instead of a fresh loop.

What it is

What is the prefix sum pattern?

A prefix sum at index i is the total of every value from the start through i. Once those totals exist, the sum of any later slice is the total at its end minus the total just before its start. You pay for one pass up front, then each range is a subtraction.

  • Build the prefixes. Walk once. Each new total is the previous total plus the value that just arrived. An empty input stays empty.
  • Read a range. The sum from i through j is prefix[j] minus prefix[i - 1]. When i is 0, there is no earlier prefix, so the answer is prefix[j].
Prefix through index 2
prefix6

Previous total 3, plus 3, is 6

WindowLStartRThrough here

When to use it

How do you recognize a prefix sum problem?

Read the statement for these signals before you add the same numbers again.

Phrases to watch for

  • running total
  • sum of a subarray
  • from the start through here
  • range sum
  • product of every other value
  • many ranges on one array
  • do not use division
  1. 1

    The same prefix is needed more than once

    Each index, or each query, asks for a total that includes everything before it.

  2. 2

    A range sum should not restart from zero

    The slice is contiguous, and you would otherwise add overlapping numbers again.

  3. 3

    You can split a product or a total into a left part and a right part

    The value at i is left-of-i combined with right-of-i. Both sides are prefixes, one walked forward and one walked backward.

Looks similar, but isn’t

  • The slice moves by adding one value and dropping another

    If you only need the current window, Sliding Window updates that one total. You do not have to store every prefix.

  • You need the complement of a prefix, not the prefix itself

    “Has this total been seen before?” is a Hash Map of prefixes. The prefix is the key. The map answers the lookup.

  • The row is sorted and you want a pair

    Two Pointers moves the ends. A running total does not tell you which end is too big.

Worked example

How does it work on running totals?

Each minute has a count of arrivals. Return a new list where each minute holds the total from the start of the day through that minute. An empty input stays empty. This is the prefix itself, and one of the problems you can practice below.

TypeScriptrunningTotals
function runningTotals(nums: number[]): number[] {  const totals: number[] = [];  let sum = 0;   for (const value of nums) {    // Each new total is the previous total plus one value.    sum += value;    totals.push(sum);  }   return totals;}

The new total reuses the previous total.

Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.

Complexity

  • TimeO(n)

    Each value is added once. Nothing is added a second time.

  • SpaceO(n)

    The result holds one total per input value. The running sum itself is one number.

A range from two prefixes

The sum from index 1 through 3 is the prefix at 3 minus the prefix at 0: 10 - 1 = 9, which is 2 + 3 + 4.

Products of every other value

Walk a left product forward and a right product backward. Position i is the left product times the right product. No division, so a zero does not break the rest of the row.

Step by step on [1, 2, 3, 4]

  1. 1

    Start from 0. The first value is 1, so the first total is 1.

  2. 2

    Add 2 to the previous total. 1 + 2 = 3. The list is [1, 3].

  3. 3

    Add 3. 3 + 3 = 6. The prefix through index 2 is 6.

  4. 4

    Add 4. 6 + 4 = 10. Return [1, 3, 6, 10].

Common mistakes

What mistakes do people make with prefix sum?

  • Adding from the start at every index

    Rebuilding each total from index 0 repeats work you already did. A row of n values becomes about n² additions.

    InsteadKeep one running sum. The next total is that sum plus the new value.

  • Subtracting a prefix that does not exist

    A range that starts at index 0 has no prefix before it. Reaching for prefix[-1] reads the wrong number, or crashes.

    InsteadIf the range starts at 0, the answer is the prefix at the end. Subtract prefix[i - 1] only when i is at least 1.

  • Using division to skip one value

    The product of every other value is a prefix problem. Division fails when a value is 0, and the problem often forbids it.

    InsteadBuild the product to the left of i and the product to the right of i, then multiply those two.

  • Forgetting the empty input

    An empty morning has no minutes. Returning [0] invents a total that was never counted.

    InsteadIf the input is empty, return an empty list. Do not seed the result with 0 unless the problem says the total starts at 0 as an entry.

Practice it in Algofily

Which Algofily problems train prefix sum?

2 problems are tagged Prefix Sum. One builds the running totals. The other builds the product of every other value from a left prefix and a right prefix.

A lock means the problem opens after you create an account. Pair With Target is open to try without one.

Start Learning.

Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.