Skip to content
StackDecode
Array techniquesAnimated

Prefix Sum

Store running totals so any range sum is one subtraction.

Time

O(n) build, O(1) query

Extra space

O(n)

Use it for

Many range-sum queries on fixed data.

How it works

  1. Build a new array P where P[i] is the sum of all items before index i (P[0] = 0).
  2. The sum of any range [l, r] is then P[r+1] − P[l]: one subtraction, no loop.
  3. Building P costs O(n) once; every query after that is O(1).

Watch it run

Loading animation…