Skip to main content

Prefix Sum

What prefix sum means, when precomputing cumulative values turns expensive range queries into cheap answers.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

Prefix sum is a way to precompute the running total of an array.

That way, instead of summing a range from scratch every time, you answer it from the difference between cumulative values.

When to use it

It appears when:

  • there are many range sum queries
  • the array does not change constantly
  • you want to trade preprocessing for faster answers

Common mistake

The classic mistake is memorizing the formula without understanding the gain.

The formula is not the point.

The point is turning many O(n) sums into O(1) queries.

Better question

Before using it, ask:

  1. will I query many intervals?
  2. is preprocessing worth it?
  3. does the structure change so often that the cumulative data becomes useless?

Keep exploring