Lesson 6 · Linear structures

Prefix Sums

A prefix sum array stores the running total of an array, so the sum of any range is the difference of two stored totals. One O(n) pass up front makes every later range sum O(1).

Prefix Sums concept diagramA visual explanation of the layout and operations shown in this lesson.each prefix stores the total up to that index314150348914valuesprefixP[0] = 0 makes every range sum one subtraction: P[j+1] − P[i]
1

What a Prefix Sum Array Is

  1. Make P with n + 1 slots and set P[0] = 0
  2. For k from 1 to n: P[k] = P[k−1] + A[k−1]
  3. For A = [3, 1, 4, 1, 5, 9] this gives P = [0, 3, 4, 8, 9, 14, 23]

A prefix sum is the total of an array's first few values. A prefix sum array P stores all of them: P[k] is the sum of the first k values, A[0] to A[k−1]. Another name is a cumulative sum or running total.

It exists to answer many range questions fast. Adding up A[i..j] with a loop costs up to n steps, so q questions cost O(n·q): with 100,000 values and 100,000 questions, that is about ten billion additions. The loops overlap, so most of that work is repeated. A prefix array does the adding once.

Give P one more slot than A. P[0] = 0 is the sum of nothing, and each later slot adds one value to the slot before it.

  • One pass: O(n) time, O(n) extra space
  • The last slot is the total of the whole array
2

Range Sum Query in O(1)

P[j+1] is the sum of A[0..j] and P[i] is the sum of A[0..i−1]. Subtract them and the shared front part cancels, leaving A[i..j]. So each range sum query is one subtraction: sum(i..j) = P[j+1] − P[i]. In the example, sum(1..3) = P[4] − P[1] = 9 − 3 = 6.

The leading zero is what makes a range that starts at 0 work the same way: sum(0..2) = P[3] − P[0] = 8. Without it you need an if i == 0 branch, and forgetting the branch is the classic bug. In Python it does not even crash: index −1 reads the last slot and the answer is silently wrong.

Some books use the inclusive form, Q[k] = A[0] + ... + A[k], with n slots; then sum(i..j) = Q[j] − Q[i−1]. Both are fine. Pick one per program and stick to it, because mixing them gives answers off by exactly one value.

  • sum(i..j) = P[j+1] − P[i] with the n + 1 form
  • If the input is not needed later, P can overwrite A in place (inclusive form)
3

When the Prefix Sum Technique Does Not Fit

The prefix sum technique assumes the array does not change. Changing A[k] makes every prefix from P[k+1] onward wrong, and fixing them costs O(n). If values change often, use a Fenwick tree or a segment tree, which give O(log n) for both updates and queries. The opposite job, adding to whole ranges and reading values afterwards, is what difference arrays do.

It also needs an operation that can be undone. Subtraction undoes addition, and XOR undoes itself, so prefix XOR works the same way: xor(i..j) = P[j+1] ^ P[i]. Products work only without zeros, since one zero wipes out every later prefix. Minimum and maximum cannot be undone at all: knowing the minimum of A[0..j] and of A[0..i−1] says nothing about A[i..j], because the smallest value may sit in the part you are removing. Range minimum needs a sparse table or a segment tree.

A useful special case is a prefix count: write 1 where a value meets some condition and 0 elsewhere, then take prefix sums. The count of matching values in any range is one subtraction.

Range sums: picking a structure
StructureBuildQueryUpdate one value
Loop over the rangenoneO(n)O(1)
Prefix sum arrayO(n)O(1)O(n)
Fenwick treeO(n)O(log n)O(log n)
Segment treeO(n)O(log n)O(log n)
  • Static array, many queries: prefix sums
  • Sum and XOR work; min and max do not
Key reference

Terms, operations, and practical uses

The array

  • PrefixThe first k values of an array. The empty prefix (k = 0) has sum 0.
  • P[k]The sum of A[0] to A[k−1]. P has n + 1 slots, and P[n] is the total of the whole array.
  • Inclusive formQ[k] = A[0] + ... + A[k] with n slots. Queries become Q[j] − Q[i−1] and need a special case for i = 0.

Using it

  • Range sumsum(i..j) = P[j+1] − P[i]. The shared front part cancels.
  • Running totalThe prefix sum so far while walking the array once, without storing all of P.
  • Seed {0: 1}Starts the hash map with the empty prefix so subarrays that begin at index 0 are counted.

Limits

  • Invertible operationOne that can be undone, like addition (by subtraction) or XOR (by itself). Min and max cannot.
  • Static dataPrefix sums assume no updates; one change makes every later prefix wrong.
  • Grid versionSums of top-left rectangles; any rectangle sum is four lookups by inclusion and exclusion.
Implementation

Code in Python, C++ and Java

def build_prefix(a):
    p = [0] * (len(a) + 1)
    for k in range(1, len(a) + 1):
        p[k] = p[k - 1] + a[k - 1]
    return p


def range_sum(p, i, j):
    return p[j + 1] - p[i]


def count_subarrays(b, k):
    seen = {0: 1}  # the empty prefix
    running = count = 0
    for value in b:
        running += value
        count += seen.get(running - k, 0)
        seen[running] = seen.get(running, 0) + 1
    return count


a = [3, 1, 4, 1, 5, 9]
p = build_prefix(a)
print("P =", " ".join(map(str, p)))
print("sum(1..3) =", range_sum(p, 1, 3))
print("sum(0..2) =", range_sum(p, 0, 2))
print("subarrays of [1, 2, -1, 1, 2] with sum 3:", count_subarrays([1, 2, -1, 1, 2], 3))
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

vector<long long> buildPrefix(const vector<int>& a) {
    vector<long long> p(a.size() + 1, 0);
    for (size_t k = 1; k <= a.size(); k++) p[k] = p[k - 1] + a[k - 1];
    return p;
}

long long rangeSum(const vector<long long>& p, int i, int j) {
    return p[j + 1] - p[i];
}

int countSubarrays(const vector<int>& b, int k) {
    unordered_map<long long, int> seen{{0, 1}};  // the empty prefix
    long long running = 0;
    int count = 0;
    for (int value : b) {
        running += value;
        auto it = seen.find(running - k);
        if (it != seen.end()) count += it->second;
        seen[running]++;
    }
    return count;
}

int main() {
    vector<int> a = {3, 1, 4, 1, 5, 9};
    vector<long long> p = buildPrefix(a);
    cout << "P =";
    for (long long x : p) cout << " " << x;
    cout << "\n";
    cout << "sum(1..3) = " << rangeSum(p, 1, 3) << "\n";
    cout << "sum(0..2) = " << rangeSum(p, 0, 2) << "\n";
    cout << "subarrays of [1, 2, -1, 1, 2] with sum 3: " << countSubarrays({1, 2, -1, 1, 2}, 3) << "\n";
}
import java.util.HashMap;
import java.util.Map;

public class Main {
    static long[] buildPrefix(int[] a) {
        long[] p = new long[a.length + 1];
        for (int k = 1; k <= a.length; k++) p[k] = p[k - 1] + a[k - 1];
        return p;
    }

    static long rangeSum(long[] p, int i, int j) {
        return p[j + 1] - p[i];
    }

    static int countSubarrays(int[] b, int k) {
        Map<Long, Integer> seen = new HashMap<>();
        seen.put(0L, 1);  // the empty prefix
        long running = 0;
        int count = 0;
        for (int value : b) {
            running += value;
            count += seen.getOrDefault(running - k, 0);
            seen.merge(running, 1, Integer::sum);
        }
        return count;
    }

    public static void main(String[] args) {
        int[] a = {3, 1, 4, 1, 5, 9};
        long[] p = buildPrefix(a);
        StringBuilder sb = new StringBuilder("P =");
        for (long x : p) sb.append(" ").append(x);
        System.out.println(sb);
        System.out.println("sum(1..3) = " + rangeSum(p, 1, 3));
        System.out.println("sum(0..2) = " + rangeSum(p, 0, 2));
        System.out.println("subarrays of [1, 2, -1, 1, 2] with sum 3: " + countSubarrays(new int[]{1, 2, -1, 1, 2}, 3));
    }
}
Watch it run

Step through it

Running on A = [3, 1, 4, 1, 5, 9]; then B = [1, 2, -1, 1, 2], k = 3

P has n + 1 slotsA301142135495P00123456P[k] = A[0] + ... + A[k-1] (the first k values, so P[k] leaves out A[k])P[0] = 0
Step 1

P[0] = 0: the empty prefix

P[k] will hold the sum of the first k values of A, so P needs n + 1 = 7 slots. P[0] is the sum of no values at all, which is 0. It looks like padding, but it is what lets a range that starts at index 0 use the same formula as every other range.

Output
1 / 15
4

Counting Subarrays with a Hash Map

  1. map = {0: 1}, running = 0, count = 0
  2. For each value: running += value
  3. count += map[running − k] (0 if missing)
  4. map[running] += 1

The most common interview use reads the formula backwards. A subarray ending at j sums to k when P[j+1] − P[i] = k, that is, when an earlier prefix equals P[j+1] − k. So the number of such subarrays is the number of earlier prefixes with that value.

Walk the array once with a running total and a hash map from prefix value to how often it has appeared. At each position, add map[running − k] to the answer, then record the running total. This solves subarray sum equals k in O(n) time, and unlike a sliding window it works with negative numbers.

Start the map as {0: 1}. That entry is the empty prefix, and it is the only way a subarray starting at index 0 gets counted. Leave it out and the code is right on every test where no answer starts at the front, then fails on the rest.

5

Prefix Sums on a Grid

The idea extends to a matrix. Let S[r][c] be the sum of the rectangle from the top-left corner to row r−1, column c−1, with an extra zero row and column. Build it with S[r][c] = M[r−1][c−1] + S[r−1][c] + S[r][c−1] − S[r−1][c−1]; the last term was added twice.

The sum of any rectangle is then four lookups: the big corner, minus the strip above, minus the strip to the left, plus the corner that was removed twice. Build is O(rows × cols); each query is O(1). This is the whole solution to range sum query 2D.

  • One extra zero row and column, as in 1D
  • Rectangle = big − top − left + top-left
6

Complexity and Edge Cases

The cost is paid once, then each query is constant.

  • Time: O(n) to build, O(1) per range query, O(n) for the hash map count
  • Space: O(n) for P, or O(1) extra if A is overwritten in place
  • Empty array: P = [0], and the only valid range is empty
  • Large values: prefix totals can overflow a 32-bit int long before single values do; use 64-bit
  • Related tricks: pivot index compares a prefix with its suffix, and product of array except self uses prefix and suffix products