Somewhat Frequent
0/11

# Introduction to Prefix Sums

Authors: Darren Yao, Dustin Miao

Computing range sum queries in constant time over a fixed 1D array.

Focus Problem – read through this problem before continuing!

## Resources

IUSACO

module is based off this

CPH

rather brief

PAPS

also rather brief

## 1D Prefix Sums

Let's say we have a one-indexed integer array $\texttt{arr}$ of size $N$ and we want to compute the value of

$\texttt{arr}[a]+\texttt{arr}[a+1]+\cdots+\texttt{arr}[b]$

for $Q$ different pairs $(a,b)$ satisfying $1\le a\le b\le N$. We'll use the following example with $N = 6$:

Index $i$123456
$\texttt{arr}[i]$164253

Naively, for every query, we can iterate through all entries from index $a$ to index $b$ to add them up. Since we have $Q$ queries and each query requires a maximum of $\mathcal{O}(N)$ operations to calculate the sum, our total time complexity is $\mathcal{O}(NQ)$. For most problems of this nature, the constraints will be $N, Q \leq 10^5$, so $NQ$ is on the order of $10^{10}$. This is not acceptable; it will almost certainly exceed the time limit.

Instead, we can use prefix sums to process these array sum queries. We designate a prefix sum array $\texttt{prefix}$. First, because we're 1-indexing the array, set $\texttt{prefix}=0$, then for indices $k$ such that $1 \leq k \leq n$, define the prefix sum array as follows:

$\texttt{prefix}[k]=\sum_{i=1}^{k} \texttt{arr}[i]$

Basically, what this means is that the element at index $k$ of the prefix sum array stores the sum of all the elements in the original array from index $1$ up to $k$. This can be calculated easily in $\mathcal{O}(N)$ by the following formula for each $1\le k\le n$:

$\texttt{prefix}[k]=\texttt{prefix}[k-1]+\texttt{arr}[k]$

For the example case, our prefix sum array looks like this:

Index $i$0123456
$\texttt{prefix}[i]$01711131821

Now, when we want to query for the sum of the elements of $\texttt{arr}$ between (1-indexed) indices $a$ and $b$ inclusive, we can use the following formula:

$\sum_{i=L}^{R} \texttt{arr}[i] = \sum_{i=1}^{R} \texttt{arr}[i] - \sum_{i=1}^{L-1} \texttt{arr}[i]$

Using our definition of the elements in the prefix sum array, we have

$\sum_{i=L}^{R} \texttt{arr}[i]= \texttt{prefix}[R]-\texttt{prefix}[L-1]$

Since we are only querying two elements in the prefix sum array, we can calculate subarray sums in $\mathcal{O}(1)$ per query, which is much better than the $\mathcal{O}(N)$ per query that we had before. Now, after an $\mathcal{O}(N)$ preprocessing to calculate the prefix sum array, each of the $Q$ queries takes $\mathcal{O}(1)$ time. Thus, our total time complexity is $\mathcal{O}(N+Q)$, which should now pass the time limit.

Let's do an example query and find the subarray sum between indices $a = 2$ and $b = 5$, inclusive, in the 1-indexed $\texttt{arr}$. From looking at the original array, we see that this is

$\sum_{i=2}^{5} \texttt{arr}[i] = 6 + 4 + 2 + 5 = 17.$
Index $i$ 1 2 3 4 5 6
$\texttt{arr}[i]$ 1 6 4 2 5 3

Using prefix sums:

$\texttt{prefix} - \texttt{prefix} = 18 - 1 = 17.$
Index $i$ 0 1 2 3 4 5 6
$\texttt{prefix}[i]$ 0 1 7 11 13 18 21

These are also known as partial sums.

## Solution - Static Range Sum

C++

In C++ we can use std::partial_sum, although it doesn't shorten the code by much.

#include <bits/stdc++.h>using namespace std;
#define sz(x) (int)size(x)
using ll = long long;using vl = vector<ll>;
vl psum(const vl& a) {	vl psum(sz(a)+1);

Java

import java.util.*;import java.io.*;
public class Main{	static int N, Q;	public static void main(String[] args) throws IOException{		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));		PrintWriter writer = new PrintWriter(System.out);		StringTokenizer st = new StringTokenizer(reader.readLine());		N = Integer.parseInt(st.nextToken());

Python

def psum(a):	psum=	for i in a:		psum.append(psum[-1]+i) # psum[-1] is the last element in the list	return psum
N, Q = map(int, input().split())a = list(map(int, input().split()))p = psum(a)
for i in range(Q):	l, r = map(int, input().split())	print(p[r]-p[l])

## Problems

StatusSourceProblem NameDifficultyTags
SilverVery Easy
Show TagsPrefix Sums
SilverEasy
Show TagsPrefix Sums
SilverEasy
Show TagsPrefix Sums
CSESEasy
Show TagsPrefix Sums
CSESEasy
Show TagsPrefix Sums
SilverEasy
Show TagsPrefix Sums
Old BronzeNormal
Show TagsPrefix Sums
CFNormal
Show TagsMath, Prefix Sums
ACNormal
Show TagsPrefix Sums
ACHard
Show TagsPrefix Sums

### Warning!

"Haybale Stacking" isn't submittable on the USACO website. Use this link to submit.

## Quiz

What is the optimal time complexity of calculating the prefix sum array of some array of length $n$?

Question 1 of 4

### Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!