Prefix sums
A prefix-sum array stores the running total up to each index so any range sum can be answered in O(1) after O(n) setup. The same idea works for counts, xors, and other invertible aggregates.
Detailed Explanation
Summing a[left:right] every time is O(n) per query. If you will do it many times, pay O(n) once. Let pref[0] = 0 and pref[i+1] = pref[i] + a[i]. Then the sum of a[left:right] (Python slice, right exclusive) is pref[right] - pref[left]. The extra zero at the front means you never special-case an empty prefix.
The aggregate must have an inverse. Addition has subtraction. XOR has XOR. Multiplication has division (with zeros as a trap). Minimum does not have an inverse; a range minimum needs a different structure (sparse table, segment tree).
2D prefix sums extend the idea to subrectangles with inclusion-exclusion: S[x2][y2] - S[x1][y2] - S[x2][y1] + S[x1][y1]. Difference arrays are the dual: you add a delta at left and subtract it at right, then prefix-sum once to materialise all range updates.
In Python, build pref with a loop or itertools.accumulate. Watch types: a prefix of ints stays exact. A prefix of floats accumulates rounding error; for money, keep cents as int.
Prefix sums trade O(n) space for fast queries. If you only need one range, just sum the slice. If the array changes often, a Fenwick tree or segment tree keeps prefixes updatable in O(log n).
Off-by-one is the usual bug. Decide whether pref[i] includes a[i], write it down, and use one convention in every query.
Code Examples
def prefix(nums: list[int]) -> list[int]:
pref = [0] * (len(nums) + 1)
for i, value in enumerate(nums):
pref[i + 1] = pref[i] + value
return pref
def range_sum(pref: list[int], left: int, right: int) -> int:
"""Sum of nums[left:right]."""
return pref[right] - pref[left]
pref = prefix([2, 1, 5, 1])
print(range_sum(pref, 1, 3)) # 1 + 5 = 6from itertools import accumulate
print(list(accumulate([2, 1, 5, 1]))) # [2, 3, 8, 9] <- no leading 0# Difference array: add 3 to nums[1:4].
n = 5
delta = [0] * (n + 1)
delta[1] += 3
delta[4] -= 3
from itertools import accumulate
print(list(accumulate(delta[:-1]))) # [0, 3, 3, 3, 0]Common Gotchas
Forgetting the leading zero
`pref[right] - pref[left - 1]` then blows up when `left == 0`.
Floats drift
do not prefix-sum currency as `float`. Use integers.
Updates make a static prefix stale
rebuild, or use a Fenwick tree.
`accumulate` does not insert `0`
add it yourself if you want the exclusive convention.