Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Prefix Sums & Suffix Sums

Precompute once, then answer any range sum in O(1).

A sensor logs one reading per second for a day, 86,40086{,}400 numbers, and then 10510^5 questions arrive: "what was the total between second ll and second rr?" Looping over every range can cost about 8.6×1098.6\times10^9 additions. One extra array of running totals answers each question with a single subtraction.

What you’ll learn

  • Build the prefix array with P[0]=0P[0]=0 and P[i+1]=P[i]+a[i]P[i+1]=P[i]+a[i], and prove that the inclusive range sum of a[l..r]a[l..r] is P[r+1]−P[l]P[r+1]-P[l].
  • Decide which operations allow range queries from prefix arrays (sums, XOR, counts) and which do not (minimum, maximum), and combine prefix and suffix arrays.
  • Apply many range additions in O(1)O(1) each with a difference array, then rebuild the array in one O(n)O(n) pass.
  • Count the subarrays with sum kk, negative numbers included, with prefix sums and a hash map.
  • Recognize prefix-sum problems from their statements and constraints, and avoid their classic bugs.

Precompute once, subtract per query

The brute force answers a range query "the sum of a[l..r]a[l..r], inclusive" with a loop: r−l+1r-l+1 additions, so O(n)O(n) per query and O(nq)O(nq) for qq queries. The waste is plain: every query re-adds numbers that earlier queries already added.

Store running totals once instead. The prefix-sum array PP has n+1n+1 entries,

P[0]=0,P[i+1]=P[i]+a[i](0≤i<n),P[0]=0,\qquad P[i+1]=P[i]+a[i]\quad(0\le i<n),

so P[i]P[i] is the sum of the first ii elements, a[0..i−1]a[0..i-1], and P[0]P[0] is the sum of no elements at all.

∑i=lra[i]  =  P[r+1]−P[l](0≤l≤r<n)\sum_{i=l}^{r} a[i] \;=\; P[r+1]-P[l]\qquad(0\le l\le r<n)
Every inclusive range sum is one subtraction: "everything up to rr" minus "everything before ll".
DerivationWhy the subtraction is exact
  1. P[j]=∑i=0j−1a[i](0≤j≤n)P[j]=\sum_{i=0}^{j-1}a[i]\qquad(0\le j\le n)

    By induction on jj (the base case is P[0]=0P[0]=0), each entry is the sum of a prefix:

  2. P[r+1]−P[l]=∑i=0ra[i]−∑i=0l−1a[i]=∑i=lra[i]P[r+1]-P[l]=\sum_{i=0}^{r}a[i]-\sum_{i=0}^{l-1}a[i]=\sum_{i=l}^{r}a[i]

    For l≤rl\le r, both P[r+1]P[r+1] and P[l]P[l] contain a[0..l−1]a[0..l-1], and that common part cancels:

  3. ∑i=lr(P[i+1]−P[i])=P[r+1]−P[l]\sum_{i=l}^{r}\big(P[i+1]-P[i]\big)=P[r+1]-P[l]

    Seen another way, a[i]=P[i+1]−P[i]a[i]=P[i+1]-P[i], and a sum of consecutive differences telescopes. Because P[0]=0P[0]=0, ranges that start at index 0 need no special case.

Predict before you look

For a=[3,−1,4,1,−5,9,2,−6]a=[3,-1,4,1,-5,9,2,-6] the prefix array is P=[0,3,2,6,7,2,11,13,7]P=[0,3,2,6,7,2,11,13,7]. What is the sum of a[3..6]a[3..6], inclusive?

Show the answer

7

P[7]−P[3]=13−6=7P[7]-P[3]=13-6=7, and indeed 1−5+9+2=71-5+9+2=7. The classic slip P[6]−P[3]=11−6=5P[6]-P[3]=11-6=5 is the sum of a[3..5]a[3..5]: it drops a[6]a[6].

Code it, then generalize: what can be prefixed?

python
def build_prefix(a):
    P = [0] * (len(a) + 1)          # P[0] = 0: the empty prefix
    for i, x in enumerate(a):
        P[i + 1] = P[i] + x
    return P                        # same as list(itertools.accumulate(a, initial=0))

def range_sum(P, l, r):             # inclusive [l, r], 0-indexed
    return P[r + 1] - P[l]

P = build_prefix([3, -1, 4, 1, -5, 9, 2, -6])
print(P)                            # [0, 3, 2, 6, 7, 2, 11, 13, 7]
print(range_sum(P, 2, 5))           # 4 + 1 - 5 + 9 = 9

Building PP takes Θ(n)\Theta(n) time and Θ(n)\Theta(n) extra space; each query takes Θ(1)\Theta(1) time in the worst case. Answering qq queries costs O(n+q)O(n+q) instead of O(nq)O(nq).

OperationHow to undo itRange query from prefix arrays?
SumSubtractionYes: P[r+1]−P[l]P[r+1]-P[l]
XORXOR again, since x⊕x=0x\oplus x=0Yes: X[r+1]⊕X[l]X[r+1]\oplus X[l]
Count of a property (letter "a", even values)SubtractionYes: one prefix array per property, e.g. 26 for lowercase letters
ProductDivision, or a modular inverseYes if no factor is zero; otherwise keep a prefix count of zeros beside the product of the nonzero values
Minimum, maximum, gcdNone: min⁡(x,y)\min(x,y) forgets the larger valueOnly prefixes a[0..r]a[0..r]; general ranges need a sparse table or a segment tree
Any associative operation has prefix values (parallel computing calls computing all of them a scan), but only invertible ones answer arbitrary ranges.
Check your understanding

With O(n)O(n) preprocessing into prefix arrays only, which query can you not answer in O(1)O(1)?

  1. The XOR of a[l..r]a[l..r]
  2. The number of vowels in s[l..r]s[l..r]
  3. The maximum of a[l..r]a[l..r]
  4. The sum of squares a[l]2+⋯+a[r]2a[l]^2+\cdots+a[r]^2
Show the answer

C. The maximum of a[l..r]a[l..r]

Maximum has no inverse: knowing max⁡(a[0..r])\max(a[0..r]) and max⁡(a[0..l−1])\max(a[0..l-1]) tells you nothing about a[l..r]a[l..r] when the overall maximum lies before ll. The other three are prefix differences of a group operation.

Suffix arrays: looking both ways

Suffix sums run the other way: S[n]=0S[n]=0 and S[i]=a[i]+S[i+1]S[i]=a[i]+S[i+1], so S[i]S[i] is the sum of a[i..n−1]a[i..n-1]. Many problems ask each index about everything to its left and everything to its right at once. Precompute both directions and every index sees both sides in O(1)O(1).

An equilibrium index ii has P[i]=S[i+1]P[i]=S[i+1]: the elements before it balance the elements after it. In [2,5,−1,3,4][2,5,-1,3,4] it is index 2, since 2+5=3+4=72+5=3+4=7.

python
def product_except_self(a):
    n = len(a)
    out = [1] * n
    left = 1
    for i in range(n):              # out[i] = product of a[0..i-1]
        out[i] = left
        left *= a[i]
    right = 1
    for i in range(n - 1, -1, -1):  # times the product of a[i+1..n-1]
        out[i] *= right
        right *= a[i]
    return out

print(product_except_self([2, 3, 0, 4]))   # [0, 0, 24, 0]

The product of all other elements, without division: a prefix product times a suffix product, O(n)O(n) time and O(1)O(1) extra space beyond the output. Dividing the total by a[i]a[i] fails as soon as some a[i]=0a[i]=0.

Think first Bars of heights [3,0,2,0,4,1,2][3,0,2,0,4,1,2] stand side by side and it rains. Water above bar ii rises to the lower of the tallest bar on its left and the tallest on its right (both including bar ii). How do prefix and suffix maxima compute the total, and what is it?

Let L[i]=max⁡(h[0..i])L[i]=\max(h[0..i]) and R[i]=max⁡(h[i..n−1])R[i]=\max(h[i..n-1]), one left-to-right and one right-to-left pass. Bar ii holds min⁡(L[i],R[i])−h[i]\min(L[i],R[i])-h[i]. Here L=[3,3,3,3,4,4,4]L=[3,3,3,3,4,4,4], R=[4,4,4,4,4,2,2]R=[4,4,4,4,4,2,2], and the water is 0+3+1+3+0+1+0=80+3+1+3+0+1+0=8. Maximum has no inverse, but this problem only ever asks about whole prefixes and whole suffixes, never a range in the middle. (The two-pointer lesson solves it with O(1)O(1) extra space.)

Range updates: the difference array

Now flip the workload: many range updates "add vv to a[l..r]a[l..r]", and the array is read only at the end. Looping costs O(n)O(n) per update. A difference array records only where neighboring values change:

D[0]=a[0],D[i]=a[i]−a[i−1](1≤i<n).D[0]=a[0],\qquad D[i]=a[i]-a[i-1]\quad(1\le i<n).

Prefix sums of DD give back aa. Adding vv to the whole block a[l..r]a[l..r] changes only two differences: the step up at ll and the step down after rr. So an update is D[l]+=vD[l] \mathrel{+}= v and D[r+1]−=vD[r+1] \mathrel{-}= v, and one prefix pass at the end rebuilds aa: O(n+q)O(n+q) for qq updates.

python
def apply_range_adds(n, updates):
    D = [0] * (n + 1)               # one spare slot, so r + 1 never overflows
    for l, r, v in updates:         # add v to a[l..r], inclusive
        D[l] += v
        D[r + 1] -= v
    a, run = [0] * n, 0
    for i in range(n):              # one prefix pass rebuilds the array
        run += D[i]
        a[i] = run
    return a

print(apply_range_adds(8, [(1, 4, 5), (3, 6, -2), (0, 2, 1)]))
# [1, 6, 6, 3, 3, -2, -2, 0]

Prefix sums and differences undo each other, just as integration and differentiation do. When reads are interleaved with the updates, keep DD in a Fenwick tree: a range update becomes two point updates and reading a[i]a[i] becomes a prefix sum, each O(log⁡n)O(\log n) (see Segment Trees & Fenwick Trees).

Subarrays with sum k: prefix sums meet a hash map

How many subarrays have sum exactly kk? The brute force checks all n(n+1)/2n(n+1)/2 of them. With negative numbers a sliding window fails, because extending a window can make its sum go down as well as up.

Prefix sums turn subarrays into pairs: a[i..j−1]a[i..j-1] has sum kk exactly when P[j]−P[i]=kP[j]-P[i]=k with i<ji<j. So scan jj from left to right and ask how many earlier prefixes equal P[j]−kP[j]-k. A hash map from prefix value to the number of times it has occurred answers that in O(1)O(1) expected time.

python
from collections import defaultdict

def count_subarrays(a, k):
    seen = defaultdict(int)
    seen[0] = 1                     # the empty prefix P[0] = 0
    prefix = count = 0
    for x in a:
        prefix += x                 # prefix = P[j]
        count += seen[prefix - k]   # earlier i with P[i] = P[j] - k
        seen[prefix] += 1
    return count

print(count_subarrays([2, -1, 3, -2, 4, -3, 1, 2], 3))   # 4

One pass: O(n)O(n) expected time with a hash map (O(nlog⁡n)O(n\log n) worst case with a balanced search tree instead) and O(n)O(n) space.

Think first For a=[2,−1,3,−2,4,−3,1,2]a=[2,-1,3,-2,4,-3,1,2] and k=3k=3, the prefix sums are P=[0,2,1,4,2,6,3,4,6]P=[0,2,1,4,2,6,3,4,6]. Find the four pairs i<ji<j with P[j]−P[i]=3P[j]-P[i]=3. Which subarray would the code miss if it started with an empty map instead of {0:1}\{0:1\}?

(2,3)(2,3) gives a[2..2]=[3]a[2..2]=[3]; (0,6)(0,6) gives a[0..5]a[0..5]; (2,7)(2,7) gives a[2..6]a[2..6]; (6,8)(6,8) gives a[6..7]=[1,2]a[6..7]=[1,2]. Without the entry for P[0]=0P[0]=0, the pair (0,6)(0,6) is never counted: every subarray that starts at index 0 disappears, and the code returns 3. The Optimal lesson Subarray Sums: Hash Maps & Kadane's Algorithm extends this idea to divisibility, balance and longest-subarray variants.

Recognizing it

Reach for prefix arrays when you see these signals:

  • Many range questions on an array that does not change: sums, XORs or counts over a[l..r]a[l..r], with nn and qq up to about 10510^5 to 10610^6, where O(nq)O(nq) is far too slow and O(n+q)O(n+q) fits.
  • Many range additions, read only at the end: bookings, schedules, paint-the-fence updates. That is a difference array.
  • "How many subarrays have sum (or XOR) kk, or a sum divisible by kk?", especially with negative numbers: prefix values plus a hash map.
  • "For every index, combine everything to its left with everything to its right": prefix and suffix arrays.
Problem (in brief)Key ideaCost
Sums of many ranges of a fixed arrayP[r+1]−P[l]P[r+1]-P[l]O(n+q)O(n+q)
How often a letter occurs in many substringsOne prefix count per letterO(∣Σ∣ n+q)O(\abs{\Sigma}\,n+q)
Product of all other elements, no divisionPrefix product times suffix productO(n)O(n)
Apply qq range increments, then print the arrayDifference array, one rebuild passO(n+q)O(n+q)
Count subarrays with sum kk, negatives allowedCount earlier prefixes equal to P[j]−kP[j]-kO(n)O(n) expected
The five most common shapes of a prefix-sum problem.
Check your understanding

A hotel has n=106n=10^6 rooms and receives q=106q=10^6 bookings, each "rooms ll through rr need one extra cleaner tomorrow". After all bookings, you must print the number of cleaners each room needs. Which technique fits best?

  1. A loop over each booking's rooms
  2. A difference array with one rebuild pass
  3. A prefix-sum array rebuilt after every booking
  4. A hash map of prefix sums
Show the answer

B. A difference array with one rebuild pass

Every booking is a range update and all reads happen at the end: D[l]+=1D[l] \mathrel{+}= 1, D[r+1]−=1D[r+1] \mathrel{-}= 1, then one prefix pass, O(n+q)O(n+q) in total, about 3×1063\times10^6 simple steps.

cpp
#include <cstdio>
#include <vector>

int main() {
    int n, q;
    if (scanf("%d %d", &n, &q) != 2) return 0;
    std::vector<long long> P(n + 1, 0);           // P[0] = 0
    for (int i = 0; i < n; i++) {
        long long x;
        scanf("%lld", &x);
        P[i + 1] = P[i] + x;                       // 64-bit: 2e5 values of 1e9 overflow int
    }
    while (q--) {
        int l, r;                                  // 0-indexed, inclusive
        scanf("%d %d", &l, &r);
        printf("%lld\n", P[r + 1] - P[l]);
    }
}

The contest version: long long sums and C-style I/O, which is fast enough for 10610^6 queries.

Key takeaways

  • With P[0]=0P[0]=0 and P[i+1]=P[i]+a[i]P[i+1]=P[i]+a[i], the inclusive sum of a[l..r]a[l..r] is P[r+1]−P[l]P[r+1]-P[l]: Θ(n)\Theta(n) preprocessing, Θ(1)\Theta(1) per query.
  • Prefix tricks need an inverse: sums, XOR and counts answer any range, while minimum, maximum and gcd answer only prefixes and suffixes.
  • Prefix and suffix arrays together give every index "everything to my left" and "everything to my right" in O(1)O(1): products of all others, equilibrium indices, trapped rain water.
  • A difference array turns each range addition into two point updates; one prefix pass rebuilds the array, O(n+q)O(n+q) in total.
  • Subarrays with sum kk are pairs of prefixes with P[j]−P[i]=kP[j]-P[i]=k: one scan with a hash map counts them, negative numbers included.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

PP has n+1n+1 entries with P[0]=0P[0]=0 and P[i+1]=P[i]+a[i]P[i+1]=P[i]+a[i]. Which expression is the sum of a[l..r]a[l..r], inclusive?

  1. P[r]−P[l]P[r]-P[l]
  2. P[r+1]−P[l+1]P[r+1]-P[l+1]
  3. P[r+1]−P[l]P[r+1]-P[l]
  4. P[r]−P[l−1]P[r]-P[l-1]
Show the answer

C. P[r+1]−P[l]P[r+1]-P[l]

P[r+1]P[r+1] is the sum of a[0..r]a[0..r] and P[l]P[l] the sum of a[0..l−1]a[0..l-1]; their difference is exactly a[l..r]a[l..r].

Question 2

An array of 10510^5 numbers receives 10510^5 operations, each either "set a[i]a[i] to vv" or "report the sum of a[l..r]a[l..r]", in any order. Which structure fits?

  1. A prefix array, rebuilt after every change
  2. A Fenwick tree (or segment tree)
  3. A difference array
  4. A hash map of prefix sums
Show the answer

B. A Fenwick tree (or segment tree)

Updates and queries are interleaved, so the array is not static. A Fenwick tree handles a point update and a prefix sum in O(log⁡n)O(\log n) each, about 105×1710^5\times17 steps per kind of operation.

Question 3

The difference array of aa (with n=10n=10) has D[0]=a[0]D[0]=a[0] and D[i]=a[i]−a[i−1]D[i]=a[i]-a[i-1]. To add 55 to a[2..6]a[2..6], inclusive, which entries change?

  1. D[2]+=5D[2] \mathrel{+}= 5 and D[7]−=5D[7] \mathrel{-}= 5
  2. D[2..6]D[2..6] all increase by 55
  3. D[2]+=5D[2] \mathrel{+}= 5 and D[6]−=5D[6] \mathrel{-}= 5
  4. D[1]+=5D[1] \mathrel{+}= 5 and D[6]−=5D[6] \mathrel{-}= 5
Show the answer

A. D[2]+=5D[2] \mathrel{+}= 5 and D[7]−=5D[7] \mathrel{-}= 5

Inside the block every neighbor difference is unchanged. The step up happens between a[1]a[1] and a[2]a[2], which is D[2]D[2], and the step down between a[6]a[6] and a[7]a[7], which is D[7]D[7].

Question 4

You must count the subarrays with sum exactly kk, and the array contains negative numbers. Which approach is correct and runs in O(n)O(n) expected time?

  1. A sliding window that shrinks while its sum exceeds kk
  2. Sort the array, then use two pointers
  3. Scan prefix sums, counting earlier prefixes equal to P[j]−kP[j]-k in a hash map
  4. Kadane's algorithm
Show the answer

C. Scan prefix sums, counting earlier prefixes equal to P[j]−kP[j]-k in a hash map

Each subarray is a pair i<ji<j with P[j]−P[i]=kP[j]-P[i]=k. Scanning jj while counting the earlier prefix values in a hash map finds all of them in one pass.

Go deeper

Further reading

  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapter 9, "Range queries" (free online).
  • G. E. Blelloch, "Prefix sums and their applications," Technical Report CMU-CS-90-190, Carnegie Mellon University (1990).
  • P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.