Практикуйте дискретную математику

Algorithms / Prefix Sums

Least You Need to Know: Prefix Sums, Range Aggregates, and Subtracting History

Prefix sums precompute cumulative totals so a range sum becomes **one subtraction of two histories**. This is one of the highest-leverage preprocessing tricks in algorithmic problem solving.

The least you need to know

Key notation

pref[i] sum of elements up to index i
range(l, r) aggregate over a contiguous interval
pref[r] - pref[l-1] range-sum query by subtraction

Tiny worked example

  • For array `[2, 5, 1, 4]`, the prefix sums are `[2, 7, 8, 12]`.
  • The range sum from index `2` to `4` is `12 - 2 = 10`.
  • Instead of re-adding the interval each time, reuse the cumulative totals.
  • That is the main speedup provided by prefix sums.

Common mistakes

How to recognize this kind of problem

Start practice