01 / 20
\(\Sigma\)

Prefix Sums
Range Queries in C++

Learn how to precompute cumulative sums to answer range-sum queries in \( O(1) \) time after \( O(n) \) preprocessing.

C++ Algorithms

The Range Sum Problem

Given an array of \( n \) integers and many queries, each asking: "What is the sum of elements from index \( l \) to index \( r \)?"

3 1 4 1 5 9 2 0 1 2 3 4 5 6
\(\text{sum}(2, 4) = 10\)

What Is a Prefix Sum?

A prefix sum array \( P \) stores the running total of all elements from the start up to each index. Formally:

Think of it as a cumulative total: each entry in \( P \) is "the sum of everything before this point." This lets us decompose any range sum into a simple subtraction.

Build once
A single \( O(n) \) pass creates the entire prefix sum array.
Query many
Each range-sum query is answered in \( O(1) \) with one subtraction.

Why Prefix Sums Matter

Prefix sums appear constantly in competitive programming, interviews, and real-world systems whenever you need fast repeated range queries on static data.

Competitive Programming
A foundational technique: dozens of contest problems reduce to prefix sums.
Data Analytics
Cumulative frequency tables, moving averages, and histogram queries.
Image Processing
2D prefix sums power fast box-blur filters and feature detection.

The Core Formula

P: 0 3 4 8 9 14 23 25
\(P[0]\)
\(P[1]\)
\(P[2]\)
\(P[3]\)
\(P[4]\)
\(P[5]\)
\(P[6]\)
\(P[7]\)
\(\text{sum}(2, 4) = P[5] - P[2]\)
\(\color{#818cf8}14 \color{#e2e8f0}- \color{#4ade80}4 \color{#e2e8f0}= \color{#fbbf24}10\)

\( P[r+1] \) is the sum of all elements up to index \( r \). Subtracting \( P[l] \) removes the part before the range, leaving exactly the elements from \( l \) to \( r \).

Visual Intuition

\(P[r+1]: \text{sum of } A[0..r]\)
\(P[l]\)
\(A[0..l-1]\)
=
\(\text{sum}(l, r)\)
\(A[l..r]\)
− The prefix sum "telescopes" away everything outside your range. No loop needed: just one subtraction.

Brute Force vs Prefix Sums

Brute Force Prefix Sums
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) \)
Handles Updates? Yes (re-sum) No (static only)

How to Apply Prefix Sums

1
Allocate the prefix array. Create \( P \) of size \( n + 1 \). Set \( P[0] = 0 \).
2
Build the prefix sums. Loop \( i = 1 \) to \( n \): set \( P[i] = P[i-1] + A[i-1] \).
3
Answer queries. For each query \( (l, r) \): return \( P[r+1] - P[l] \).

C++ Implementation

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

// Query: sum of a[l..r] (0-indexed)
long long rangeSum(const vector<long long>& p,
                  int l, int r) {
  return p[r + 1] - p[l];
}

Example 1: Building the Array

Given \( A = [2, 5, 1, 4, 3] \), build the prefix sum array \( P \).

A: 2 5 1 4 3 0 1 2 3 4 → P: 0 2 7 8 12 15
\(P[0]\)
\(P[1]\)
\(P[2]\)
\(P[3]\)
\(P[4]\)
\(P[5]\)

Example 2: Answering Queries

Using \( A = [2, 5, 1, 4, 3] \) and \( P = [0, 2, 7, 8, 12, 15] \):

Q1
sum(1, 3) = \( P[4] - P[1] = 12 - 2 = \) 10   (elements 5 + 1 + 4)
Q2
sum(0, 4) = \( P[5] - P[0] = 15 - 0 = \) 15   (entire array)
Q3
sum(2, 2) = \( P[3] - P[2] = 8 - 7 = \) 1   (single element)

Example 3: Full Walkthrough

int main() {
  vector<int> a = {10, 20, 30, 40, 50};
  auto p = buildPrefix(a);
  // p = {0, 10, 30, 60, 100, 150}

  cout << rangeSum(p, 1, 3); // 90
  // P[4] - P[1] = 100 - 10 = 90
  // Verify: 20 + 30 + 40 = 90 ✓

  cout << rangeSum(p, 0, 0); // 10
  // P[1] - P[0] = 10 - 0 = 10 ✓
}

The 1-Indexed Variant

Some problems (and many contest templates) use 1-based indexing. The formula changes slightly:

0-indexed
\( P[i] = P[i-1] + A[i-1] \)
Query: \( P[r+1] - P[l] \)
1-indexed
\( P[i] = P[i-1] + A[i] \)
Query: \( P[r] - P[l-1] \)

Common Mistakes

✕ Off-by-One
Using \( P[r] - P[l] \) instead of \( P[r+1] - P[l] \) in 0-indexed arrays. This misses element \( A[r] \).
✕ Integer Overflow
Storing prefix sums in int when element values are large. Always use long long.
✕ Wrong Array Size
Allocating \( P \) with size \( n \) instead of \( n+1 \). This causes out-of-bounds access.

Summary Cheat Sheet

Aspect Detail
Build Time \( O(n) \)
Query Time \( O(1) \)
Space \( O(n) \) extra for \( P \)
Array Size \( n + 1 \) (one extra element)
Data Type long long to prevent overflow
Limitation Static arrays only (no updates)
Key Formula (0-idx) \( P[r+1] - P[l] \)

Question 1 of 5

Given \( A = [3, 1, 4, 1, 5] \), what is \( P[3] \) in the 0-indexed prefix sum array?

Question 2 of 5

Using 0-indexed prefix sums, the sum of elements from index \( l \) to \( r \) is:

Question 3 of 5

If \( P = [0, 5, 12, 18, 27, 33] \), what is sum(2, 4)?

Question 4 of 5

What is the time complexity to answer \( q \) range-sum queries on an array of size \( n \) using prefix sums?

Question 5 of 5

Which of the following is a limitation of the basic prefix sum technique?