Prefix sums and difference arrays

In one sentence

Precompute running totals once in O(n) and any range sum is one subtraction, O(1); the mirror trick, a difference array, makes each range update O(1).

Analogy: A car odometer: to know the distance between two stops you subtract two readings; you don't add up every kilometer again.

Build once, then every range sum is one subtraction. A difference array is the reverse: two writes per range update, one prefix pass at the end.

How it works

  • P[i] is the sum of the first i elements; P[0] = 0 removes edge cases.
  • The sum of a[i:j] is P[j] − P[i]; an inclusive [l..r] is P[r+1] − P[l].
  • 2D: four lookups per rectangle: the big corner, minus two strips, plus the overlap.
  • Difference array: diff[l] += x, diff[r+1] −= x; one prefix pass rebuilds the array.
  • Needs an inverse operation and no interleaved updates; otherwise use a Fenwick or segment tree.

Check yourself

Answer to mark it learned; your answers aren't scored.

A report answers 10⁵ "total sales from day i to day j" queries over a fixed 10⁵-day history. Each query loops over its range and the job times out. Best fix?

Go deeper

Solve it in Python 10
Full explanation

A prefix sum array stores running totals: P[0] = 0 and P[i] = a[0] + … + a[i−1]. Build it once in O(n); the sum of a[i:j] is then P[j] − P[i], in O(1). The leading zero removes the special case for ranges that start at index 0.

  • 2D: P[r][c] is the sum of the rectangle above and to the left. Any sub-rectangle takes four lookups: the big corner, minus the strip above, minus the strip to the left, plus the corner you subtracted twice.
  • Difference array: the inverse. To add x to a[l..r], do diff[l] += x and diff[r+1] −= x, O(1) per update. One prefix-sum pass at the end rebuilds the array.
  • With a hash map: counting subarrays that sum to k becomes "how many earlier prefixes equal P[j] − k?". See Hash maps, sets and prefix sums.

It works for any operation with an inverse (sum, XOR, counts), not for min or max. If updates and queries interleave, use a Fenwick tree or a segment tree: O(log n) for both.

Code Prefix sums in 1D and 2D, and a difference array
pythonPrefix sums in 1D and 2D, and a difference array
from itertools import accumulate

def build_prefix(a: list[int]) -> list[int]:
    return list(accumulate(a, initial=0))        # P[i] = sum(a[:i]), so P[0] = 0

def range_sum(P: list[int], i: int, j: int) -> int:
    return P[j] - P[i]                           # sum of a[i:j], half-open

def build_prefix_2d(g: list[list[int]]) -> list[list[int]]:
    rows, cols = len(g), len(g[0]) if g else 0        # an empty grid has no g[0]
    P = [[0] * (cols + 1) for _ in range(rows + 1)]   # extra zero row and column
    for r in range(rows):
        for c in range(cols):                    # top + left - overlap counted twice
            P[r + 1][c + 1] = g[r][c] + P[r][c + 1] + P[r + 1][c] - P[r][c]
    return P

def region_sum(P, r1: int, c1: int, r2: int, c2: int) -> int:
    # rows r1..r2-1 and columns c1..c2-1 (half-open, like the 1D version)
    return P[r2][c2] - P[r1][c2] - P[r2][c1] + P[r1][c1]

def apply_range_adds(n: int, updates: list[tuple[int, int, int]]) -> list[int]:
    diff = [0] * (n + 1)                         # spare slot for r + 1 == n
    for l, r, x in updates:                      # add x to a[l..r], inclusive
        diff[l] += x
        diff[r + 1] -= x
    return list(accumulate(diff[:n]))            # prefix sum of diff = final array
Real example

Range sum query: a = [1, 3, 4, 8, 6, 1, 4, 2] gives P = [0, 1, 4, 8, 16, 22, 23, 27, 29]. The sum of a[3:7] (8 + 6 + 1 + 4) is P[7] − P[3] = 27 − 8 = 19. Assume n = 10⁵ and 10⁵ queries: rescanning costs up to 10¹⁰ additions; prefix sums cost ~2×10⁵ steps.

Range updates on five zeros: add 2 to [1..3] and 3 to [2..4]. diff = [0, 2, 3, 0, −2] (plus a spare slot), and its prefix sum is [0, 2, 5, 5, 3].

Trade-offs +3 · −3

+ You gain

  • O(1) range sums after an O(n) build; O(1) range updates with a difference array.
  • Works with negative numbers, where a sliding window fails.
  • Extends to 2D grids, per-character counts, XOR and modular sums.

− You pay

  • O(n) extra memory; O(rows × cols) in 2D.
  • Static: one point update invalidates up to n prefix entries.
  • Needs an inverse: range min or max need a sparse table or a segment tree.

Use it when

Many range-sum queries on an array or grid that doesn't change; many range updates read once at the end; counting subarrays by sum, also with negative numbers.

Avoid it when

Updates interleaved with queries (Fenwick or segment tree), range min or max (no inverse), or a single query, where one plain loop is simpler.

Numbers to know 5
  • Build O(n), query O(1): q queries cost O(n + q) instead of O(n·q).
  • 2D: build in O(rows × cols); any rectangle sum is 4 lookups.
  • Difference array: O(1) per range update plus one O(n) pass: O(n + u) for u updates.
  • Fenwick tree, for interleaved point updates and range sums: O(log n) each.
  • The 2D form is the summed-area table (Crow, 1984), the "integral image" of Viola–Jones object detection (2001).
Common pitfalls 4
  • Mixing conventions: P[j] − P[i] is the half-open a[i:j]; an inclusive [l..r] is P[r+1] − P[l].
  • A difference array of size n: diff[r+1] is out of range when r = n − 1. Allocate n + 1.
  • 2D: forgetting to add back the top-left corner, which was subtracted twice.
  • In Java or C++, sums can overflow a 32-bit int: use long (long long in C++).
Interview questions 2

Answer out loud first, then reveal.

How do you recognize a prefix-sum problem?Show answer

I look for many range-sum queries on data that doesn't change, or a subarray-sum question a sliding window can't answer because of negative numbers. Then I precompute once: O(n) to build, O(1) per query; on a grid, the 2D version. If the input is a list of range updates and I only read at the end, I flip it into a difference array. If updates and queries interleave, I say so and move to a Fenwick tree.

The array now gets point updates between queries. What changes?Show answer

A prefix array breaks: one update changes every later prefix, O(n). I'd switch to a Fenwick tree (binary indexed tree): it stores partial sums so that a point update and a prefix query each touch O(log n) entries. A segment tree costs the same and also handles min and max. If updates are rare, rebuilding the prefix array after each one can still be the simplest correct choice.