AlgoViz

Prefix sums

medium 20 min

Write the running totals of an array into P once, with P[0] = 0, and the sum of any range a[l..r] becomes one subtraction, P[r + 1] - P[l].

Video lesson · Chapter 1 of 9

The returns counter

0:00 / 6:14

Prefix sums in 75 seconds

1:27Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Build P once. P[0] = 0 and P[i + 1] = P[i] + a[i]: n additions, n + 1 cells

Understand it

Recap

Running totals answer range questions

  • Arrays: O(1) by index

    Reading a[i] is instant, but adding up a[l..r] with a loop costs r−l+1r - l + 1 steps, every time you ask. See static arrays.

  • Hash maps: O(1) lookup

    A dict answers 'have I seen this value, and how often?' in O(1)O(1) on average. Half of this topic leans on it. See hash usage.

  • The trade

    Spend O(n)O(n) time and space once to store running totals. Every range sum after that is O(1)O(1).

Take a = [3, 1, 4, 1, 5]. Its running totals are 3, 4, 8, 9, 14. Put a 0 in front for 'nothing added yet' and you have the prefix array P = [0, 3, 4, 8, 9, 14]. Now the sum of a[1..3], that is 1+4+11 + 4 + 1, is P[4] - P[1] = 9 - 3 = 6: one subtraction instead of a loop.

Step 1

Build P with P[0] = 0

Definition and recurrence

P[i]=∑t=0i−1a[t](0≤i≤n),P[0]=0,P[i+1]=P[i]+a[i]P[i] = \sum_{t=0}^{i-1} a[t] \quad (0 \le i \le n), \qquad P[0] = 0, \qquad P[i+1] = P[i] + a[i]
P[i]P[i] is the sum of the first $i$ elements, a[0..i−1]a[0..i-1]. So PP has n+1n + 1 cells, P[0]P[0] is the empty sum and P[n]P[n] is the total.

Building the prefix array

One addition per element: O(n)O(n) time, O(n)O(n) space.

a = [3, 1, 4, 1, 5]

StepComputationP so far
0P[0] = 0[0]
1P[1] = P[0] + a[0] = 0 + 3[0, 3]
2P[2] = P[1] + a[1] = 3 + 1[0, 3, 4]
3P[3] = P[2] + a[2] = 4 + 4[0, 3, 4, 8]
4P[4] = P[3] + a[3] = 8 + 1[0, 3, 4, 8, 9]
5P[5] = P[4] + a[4] = 9 + 5[0, 3, 4, 8, 9, 14]
a has indices 0 to 4; P has indices 0 to 5. Each P[i] sits on the fence between a[i - 1] and a[i].
Python
from itertools import accumulatedef build_prefix(a):    P = [0] * (len(a) + 1)    for i in range(len(a)):        P[i + 1] = P[i] + a[i]    return Pa = [3, 1, 4, 1, 5]print(build_prefix(a))                 # [0, 3, 4, 8, 9, 14]print([0] + list(accumulate(a)))       # the same
Two ways to build it. itertools.accumulate does the running total; the leading 0 is up to you.
Edit and run it in your browser

Step 2

Any range sum in O(1)

Why one subtraction is enough

∑t=lra[t]  =  ∑t=0ra[t]⏟P[r+1]  −  ∑t=0l−1a[t]⏟P[l]  =  P[r+1]−P[l]\sum_{t=l}^{r} a[t] \;=\; \underbrace{\sum_{t=0}^{r} a[t]}_{P[r+1]} \;-\; \underbrace{\sum_{t=0}^{l-1} a[t]}_{P[l]} \;=\; P[r+1] - P[l]
Everything through rr, minus everything before ll. The shared part, indices 0 to l−1l - 1, cancels.

Queries on P = [0, 3, 4, 8, 9, 14]

QueryElementsFormulaAnswer
sum(1, 3)1 + 4 + 1P[4] - P[1] = 9 - 36
sum(0, 4)the whole arrayP[5] - P[0] = 14 - 014
sum(2, 2)just a[2]P[3] - P[2] = 8 - 44
sum(3, 4)1 + 5P[5] - P[3] = 14 - 86
Every row costs two reads and one subtraction, whatever the length of the range.

Convention

The off-by-one, settled once

Length n + 1, P[0] = 0 (use this)

  • P[i] = sum of a[0..i-1], the first ii elements.
  • sum(l, r) = P[r + 1] - P[l], no branches.
  • Matches half-open ranges: [l,r+1)[l, r+1) is P[r + 1] - P[l].
  • The same shape as the {0: 1} seed and the 2D zero border.

Length n, inclusive (avoid)

  • Q[i] = sum of a[0..i], including a[i].
  • sum(l, r) = Q[r] - Q[l - 1], which needs an if l == 0 branch.
  • In Python, forgetting the branch reads Q[-1], the total, with no error.
  • Each formula needs its own fiddly edge case.

Nothing is lost by switching to P: every original value comes back as a[i]=P[i+1]−P[i]a[i] = P[i+1] - P[i], a range of length one. That identity is also the bridge to difference arrays at the end of this page.

Cost

When prefix sums pay off

ApproachBuildPer queryq queriesExtra space
Loop over the rangenoneO(n)O(n) worstO(n⋅q)O(n \cdot q)O(1)O(1)
Prefix sumsO(n)O(n)$O(1)$$O(n + q)$O(n)O(n)
Fenwick or segment treeO(n)O(n)O(log⁡n)O(\log n)O((n+q)log⁡n)O((n + q)\log n)O(n)O(n)
Prefix sums win when the data is static and there are many queries. Trees win when values change between queries.

Paying once versus paying every time

n+q⏟prefix sumsvsn⋅q⏟loopn=q=105:  2×105 vs 1010\underbrace{n + q}_{\text{prefix sums}} \quad \text{vs} \quad \underbrace{n \cdot q}_{\text{loop}} \qquad n = q = 10^5:\ \ 2 \times 10^5 \ \text{vs}\ 10^{10}
With a hundred thousand elements and as many queries, the loop does fifty thousand times more work.

Which tool for range sums?

The original app's advice in one picture: static data and many queries means prefix sums; frequent updates means a tree.

Pattern 1

Subarray sum equals k: prefix plus a map

A run with sum k is a pair of prefixes

∑t=ija[t]=k  ⟺  P[j+1]−P[i]=k  ⟺  P[i]=P[j+1]−k\sum_{t=i}^{j} a[t] = k \iff P[j+1] - P[i] = k \iff P[i] = P[j+1] - k
Walking left to right, at each jj the number of runs ending at $j$ with sum kk is the number of earlier prefixes equal to P[j+1]−kP[j+1] - k. A dict of prefix counts answers that in O(1)O(1) average.

One pass with a map of prefix counts

Look up first, record second, so the current prefix never pairs with itself.
Python
def subarray_sum(a, k):    seen = {0: 1}                 # the empty prefix P[0] = 0    prefix = count = 0    for x in a:        prefix += x        count += seen.get(prefix - k, 0)        seen[prefix] = seen.get(prefix, 0) + 1    return countprint(subarray_sum([1, 2, 1, -2, 3], 3))   # 3print(subarray_sum([1, 1, 1], 2))          # 2print(subarray_sum([1, -1, 0], 0))         # 3: [1, -1], [0], [1, -1, 0]
LeetCode 560. On [1, 2, 1, -2, 3] with k=3k = 3 it finds [1, 2], [2, 1] and [3].
Edit and run it in your browser

Pattern 1, deeper

Three questions, three maps

QuestionMap storesSeedUpdate rule
How many runs sum to k?prefix value → count{0: 1}always add 1 after the lookup
Longest run with sum k?prefix value → first index{0: -1}set only if not present
Shortest run with sum k?prefix value → last index{0: -1}overwrite every time
How many runs with sum divisible by k?prefix % k → count{0: 1}always add 1 after the lookup
The lookup key is prefix - k for exact sums and the remainder itself for divisibility: equal remainders differ by a multiple of k.

Divisible by k means equal remainders

k∣(P[j+1]−P[i])  ⟺  P[j+1] mod k=P[i] mod k,runs=∑r=0k−1(cr2)k \mid \big(P[j+1] - P[i]\big) \iff P[j+1] \bmod k = P[i] \bmod k, \qquad \text{runs} = \sum_{r=0}^{k-1} \binom{c_r}{2}
crc_r is how many prefixes (including P[0]=0P[0] = 0) have remainder rr; any two of them bound a run. Counting as you go adds the same total.
Python
def longest_sum_k(a, k):    first = {0: -1}    prefix = best = 0    for i, x in enumerate(a):        prefix += x        if prefix - k in first:            best = max(best, i - first[prefix - k])        first.setdefault(prefix, i)      # keep the earliest index    return bestdef count_divisible(a, k):    seen = {0: 1}    prefix = count = 0    for x in a:        prefix += x        r = prefix % k                   # Python: always 0..k-1        count += seen.get(r, 0)        seen[r] = seen.get(r, 0) + 1    return countprint(longest_sum_k([1, -1, 5, -2, 3], 3))       # 4: [1, -1, 5, -2]print(count_divisible([4, 5, 0, -2, -3, 1], 5))  # 7
Longest run with sum k (first index) and runs divisible by k (remainder counts).
Edit and run it in your browser

Pattern 2

Contiguous array: turn 0/1 into a balance

Find the longest run of a binary array with as many 0s as 1s. Counting both is awkward, so count each 1 as +1+1 and each 0 as −1-1. A run is balanced exactly when its sum is 0, which is subarray sum equals kk with k=0k = 0. And since we want the longest, the map stores the first index of each balance.

Balanced run, equal balances

bt={+1a[t]=1−1a[t]=0,B[i]=∑t<ibt,#1=#0 in a[i..j]  ⟺  B[j+1]=B[i]b_t = \begin{cases} +1 & a[t] = 1 \\ -1 & a[t] = 0 \end{cases}, \quad B[i] = \sum_{t<i} b_t, \qquad \#1 = \#0 \text{ in } a[i..j] \iff B[j+1] = B[i]
The length is j−i+1j - i + 1. Storing the first index i−1i - 1 of each balance makes that i - first[balance] in the code.

Contiguous array, one index at a time

Only the first index of each balance is kept. On [0, 1, 0, 0, 1, 1, 0] the answer is 6, indices 0 to 5.
Python
def find_max_length(bits):    first = {0: -1}    balance = best = 0    for i, b in enumerate(bits):        balance += 1 if b == 1 else -1        if balance in first:            best = max(best, i - first[balance])        else:            first[balance] = i    return bestprint(find_max_length([0, 1, 0, 0, 1, 1, 0]))   # 6print(find_max_length([0, 1]))                  # 2print(find_max_length([0, 0, 0]))               # 0
LeetCode 525. O(n)O(n) time; the map holds at most 2n+12n + 1 balances, from −n-n to nn.
Edit and run it in your browser

Pattern 3

Product of array except self

Prefix times suffix

out[i]=∏t=0i−1a[t]⏟left of i⋅∏t=i+1n−1a[t]⏟right of i\text{out}[i] = \underbrace{\prod_{t=0}^{i-1} a[t]}_{\text{left of } i} \cdot \underbrace{\prod_{t=i+1}^{n-1} a[t]}_{\text{right of } i}
The same running-total idea with ×\times instead of ++. The empty product is 1, the way the empty sum P[0]P[0] is 0.

a = [1, 2, 3, 4]

i0123
left product (before i)1126
right product (after i)241241
out = left × right241286
Both products are exclusive: neither includes a[i] itself.
Python
def product_except_self(a):    n = len(a)    out = [1] * n    left = 1    for i in range(n):        out[i] = left        left *= a[i]    right = 1    for i in range(n - 1, -1, -1):        out[i] *= right        right *= a[i]    return outprint(product_except_self([1, 2, 3, 4]))       # [24, 12, 8, 6]print(product_except_self([2, 0, 3, 4]))       # [0, 24, 0, 0]
LeetCode 238. Left products go straight into out; the right product is one variable, so extra space is O(1)O(1) besides the output.
Edit and run it in your browser

2D

2D prefix sums and inclusion-exclusion

Build: add above, add left, subtract the overlap

S[i+1][j+1]=M[i][j]+S[i][j+1]+S[i+1][j]−S[i][j],S[0][⋅]=S[⋅][0]=0S[i+1][j+1] = M[i][j] + S[i][j+1] + S[i+1][j] - S[i][j], \qquad S[0][\cdot] = S[\cdot][0] = 0
S[i][j]S[i][j] is the sum of the top-left block of rows 0..i−10..i-1 and columns 0..j−10..j-1. The block above and the block to the left overlap in S[i][j]S[i][j], which was added twice.

Query: any rectangle in four reads

∑r=r1r2∑c=c1c2M[r][c]=S[r2+1][c2+1]−S[r1][c2+1]−S[r2+1][c1]+S[r1][c1]\sum_{r=r_1}^{r_2} \sum_{c=c_1}^{c_2} M[r][c] = S[r_2{+}1][c_2{+}1] - S[r_1][c_2{+}1] - S[r_2{+}1][c_1] + S[r_1][c_1]
On M = [[3, 0, 1, 4], [5, 6, 3, 2], [1, 2, 0, 1]], rows 1 to 2 and columns 1 to 2 give 21−4−9+3=1121 - 4 - 9 + 3 = 11, which is 6+3+2+06 + 3 + 2 + 0.

Inclusion-exclusion for one rectangle

Build and query use the same four-term pattern, with the signs arranged so every cell is counted exactly once.
Python
def build_2d(M):    R, C = len(M), len(M[0])    S = [[0] * (C + 1) for _ in range(R + 1)]    for i in range(R):        for j in range(C):            S[i + 1][j + 1] = M[i][j] + S[i][j + 1] + S[i + 1][j] - S[i][j]    return Sdef region_sum(S, r1, c1, r2, c2):    return S[r2 + 1][c2 + 1] - S[r1][c2 + 1] - S[r2 + 1][c1] + S[r1][c1]M = [[3, 0, 1, 4],     [5, 6, 3, 2],     [1, 2, 0, 1]]S = build_2d(M)print(region_sum(S, 1, 1, 2, 2))   # 11print(region_sum(S, 0, 0, 2, 3))   # 28, the whole matrix
LeetCode 304. O(R⋅C)O(R \cdot C) build, O(1)O(1) per rectangle.
Edit and run it in your browser

Inverse

Difference arrays: O(1) range updates

Difference and prefix sum undo each other

D[0]=a[0],D[i]=a[i]−a[i−1]⟺a[i]=∑t=0iD[t]D[0] = a[0],\quad D[i] = a[i] - a[i-1] \qquad \Longleftrightarrow \qquad a[i] = \sum_{t=0}^{i} D[t]
Adding vv to a[l..r]a[l..r] raises the step into ll by vv and the step out of rr by −v-v; every other difference is unchanged. So an update is two writes: D[l] += v, D[r + 1] -= v.
Many updates, one rebuild
  1. 1D = [0] * (n + 1)one spare slot for r + 1 = n
  2. 2Each updateD[l] += v, D[r + 1] -= v
  3. 3Prefix sum of Drun += D[i] rebuilds a
  4. 4Read the resultO(n + q) in total

Prefix sums make range reads cheap; difference arrays make range writes cheap.

Python
def apply_updates(n, updates):    D = [0] * (n + 1)    for l, r, v in updates:        D[l] += v        D[r + 1] -= v    out, run = [], 0    for i in range(n):        run += D[i]        out.append(run)    return outprint(apply_updates(6, [(1, 3, 2), (2, 5, 3), (0, 1, -1)]))   # [-1, 1, 5, 5, 3, 3]print(apply_updates(6, [(0, 2, 3), (1, 4, 2), (3, 5, 4)]))    # [3, 5, 5, 6, 6, 4]
Range addition. The bus version (LeetCode 1094, car pooling) adds people at the pickup and subtracts them at the drop-off.
Edit and run it in your browser

Wrap-up

Where it fits, and what to remember

  • Kadane's algorithm

    The best run ending at jj is P[j+1]−min⁡i≤jP[i]P[j+1] - \min_{i \le j} P[i]. Tracking the smallest prefix so far gives maximum subarray in one pass, which is Kadane in disguise.

  • Sliding window

    With non-negative numbers and a 'longest or shortest with sum at most k' question, a variable window uses O(1)O(1) space. With negatives or exact counts, use the prefix map.

  • Segment tree

    When values change between queries, a segment tree answers range sums and updates in O(log⁡n)O(\log n) each.

  • Hash usage

    Counting, first-seen indices and remainders are the dict patterns from hash usage, applied to prefix values.

Key points

  • P[i] is the sum of the first ii elements; P has n+1n + 1 cells and P[0] = 0.
  • sum(l, r) = P[r + 1] - P[l]: O(n)O(n) to build, O(1)O(1) per query, O(n+q)O(n + q) for qq queries.
  • Subarray sum equals kk: count earlier prefixes equal to prefix - k, seeded with {0: 1}, look up before recording.
  • Longest run: store the first index (seed {0: -1}). Divisible by kk: bucket by prefix % k.
  • Contiguous array: 0 as −1-1, 1 as +1+1, longest run between equal balances.
  • Product except self: exclusive prefix product times exclusive suffix product, no division.
  • 2D: build with plus above, plus left, minus corner; query with big minus top minus left plus corner.
  • Difference arrays invert prefix sums: two writes per range update, one prefix sum to read.

Sources