Prefix Sums
in Python
Learn a powerful technique to answer range-sum queries in constant time using precomputed cumulative sums.
The Range-Sum Problem
Given an array of numbers, you are asked to find the sum of elements between two indices many times. For example: "What is the sum from index \(i\) to index \(j\)?"
What Is a Prefix Sum?
A prefix sum array stores the cumulative sum of elements from the start up to each index. If the original array is \(a\), the prefix sum array \(P\) is defined as:
Notice that \(P\) has one more element than \(a\). The entry \(P[k]\) equals the sum of the first \(k\) elements of \(a\).
Building the Prefix Array
The Core Formula
Once you have the prefix sum array \(P\), the sum of any subarray \(a[i \ldots j]\) (inclusive) is computed instantly:
This works because \(P[j{+}1]\) includes everything from \(a[0]\) to \(a[j]\), and subtracting \(P[i]\) removes the elements before index \(i\). Each query now costs \(O(1)\).
Why Subtraction Works
Naive Loop vs Prefix Sum
| Naive Loop | Prefix Sum | |
|---|---|---|
| Preprocessing | None | \(O(n)\) |
| Per Query | \(O(n)\) | \(O(1)\) |
| Total for \(q\) queries | \(O(n \cdot q)\) | \(O(n + q)\) |
| Extra Space | \(O(1)\) | \(O(n)\) |
| Best When | Very few queries | Many queries |
Python Implementation
Step-by-Step Approach
Example 1: Basic Query
Given \(a = [2, 5, 1, 3, 7, 4, 6]\), find the sum from index 1 to 3 (inclusive).
Example 2: Multiple Queries
Same array \(a = [2, 5, 1, 3, 7, 4, 6]\) with \(P = [0, 2, 7, 8, 11, 18, 22, 28]\). Answer three queries:
Example 3: Full Program
Python's itertools.accumulate
Common Mistakes
Summary at a Glance
| Concept | Details |
|---|---|
| Input | Array \(a\) of \(n\) numbers |
| Prefix Array | \(P[k] = a[0] + a[1] + \cdots + a[k{-}1]\) |
| Array Length | \(P\) has \(n{+}1\) elements, starting with 0 |
| Query Formula | \(\text{sum}(i, j) = P[j{+}1] - P[i]\) |
| Build Time | \(O(n)\) |
| Query Time | \(O(1)\) |
| Space | \(O(n)\) |
Question 1 of 5
Given \(a = [3, 1, 4, 1, 5]\), what is the prefix sum array \(P\)?
Question 2 of 5
Using \(P = [0, 3, 4, 8, 9, 14]\), what is the sum of \(a[1 \ldots 3]\)?
Question 3 of 5
What is the time complexity of answering \(q\) range-sum queries on an array of length \(n\) using prefix sums?
Question 4 of 5
What Python code correctly builds a prefix sum array from list a?
Question 5 of 5
If \(P = [0, 2, 7, 8, 11, 18, 22, 28]\), what is the value of the original element \(a[4]\)?