Not Frequent
0/7

# More on Prefix Sums

Authors: Darren Yao, Neo Wang, Qi Wang

Contributors: Jesse Choe, Kevin Sheng, Brad Ma, Juheon Rhee

Max subarray sum, prefix sums in two dimensions, and a more complicated example.

## Max Subarray Sum

Focus Problem – read through this problem before continuing!

Solution

## 2D Prefix Sums

Focus Problem – read through this problem before continuing!

Now, what if we wanted to process $Q$ queries for the sum over a subrectangle of a 2D matrix with $N$ rows and $M$ columns? Let's assume both rows and columns are 1-indexed, and we use the following matrix as an example:

 0 0 0 0 0 0 0 1 5 6 11 8 0 1 7 11 9 4 0 4 6 1 3 2 0 7 5 4 2 3

Naively, each sum query would then take $\mathcal{O}(NM)$ time, for a total of $\mathcal{O}(QNM)$. This is too slow.

Let's take the following example region, which we want to sum:

 0 0 0 0 0 0 0 1 5 6 11 8 0 1 7 11 9 4 0 4 6 1 3 2 0 7 5 4 2 3

Manually summing all the cells, we have a submatrix sum of $7+11+9+6+1+3 = 37$.

The first logical optimization would be to do one-dimensional prefix sums of each row. Then, we'd have the following row-prefix sum matrix. The desired subarray sum of each row in our desired region is simply the green cell minus the red cell in that respective row. We do this for each row to get $(28-1) + (14-4) = 37$.

 0 0 0 0 0 0 0 1 6 12 23 31 0 1 8 19 28 32 0 4 10 11 14 16 0 7 12 16 18 21

Now, if we wanted to find a submatrix sum, we could break up the submatrix into a subarray for each row, and then add their sums, which would be calculated using the prefix sums method described earlier. Since the matrix has $N$ rows, the time complexity of this is $\mathcal{O}(QN)$. This might be fast enough for $Q=10^5$ and $N=10^3$, but we can do better.

In fact, we can do two-dimensional prefix sums. In our two dimensional prefix sum array, we have

$\texttt{prefix}[a][b]=\sum_{i=1}^{a} \sum_{j=1}^{b} \texttt{arr}[i][j].$

This can be calculated as follows for row index $1 \leq i \leq n$ and column index $1 \leq j \leq m$:

\begin{aligned} \texttt{prefix}[i][j] =& \, \texttt{prefix}[i-1][j]+ \texttt{prefix}[i][j-1] \\ &- \texttt{prefix}[i-1][j-1]+ \texttt{arr}[i][j] \end{aligned}

Let's calculate $\texttt{prefix}$. Try playing with the interactive widget below by clicking the buttons to see which numbers are added in each step. Notice how we overcount a subrectangle, and how we fix this by subtracting $\texttt{prefix}[i-1][j-1]$.

subtract prefix[i-1][j-1]
to get prefix[i][j]
000000
0156118
0171194
046132
075423

The submatrix sum between rows $a$ and $A$ and columns $b$ and $B$, can thus be expressed as follows:

\begin{aligned} \sum_{i=a}^{A} \sum_{j=b}^{B} \texttt{arr}[i][j]=&\,\texttt{prefix}[A][B] - \texttt{prefix}[a-1][B] \\ &- \texttt{prefix}[A][b-1] + \texttt{prefix}[a-1][b-1] \end{aligned}

Summing the blue region from above using the 2D prefix sums method, we add the value of the green square, subtract the values of the red squares, and then add the value of the gray square. In this example, we have

$65-23-6+1 = 37,$

as expected.

 0 0 0 0 0 0 0 1 6 12 23 31 0 2 14 31 51 63 0 6 24 42 65 79 0 13 36 58 83 100

Try playing with the interactive widget below by clicking the buttons to see which numbers are added in each step.

subtract prefix[a-1][B]
subtract prefix[A][b-1]
to get our result
000000
0156118
0171194
046132
075423

Since no matter the size of the submatrix we are summing, we only need to access four values of the 2D prefix sum array, this runs in $\mathcal{O}(1)$ per query after an $\mathcal{O}(NM)$ preprocessing.

### Warning!

We need to be cautious of off-by-one errors, as intervals can be inclusive, exclusive, 1-indexed, etc.

C++

#include <iostream>#include <vector>
using namespace std;
constexpr int MAX_SIDE = 1000;int tree_pref[MAX_SIDE + 1][MAX_SIDE + 1];int forest[MAX_SIDE + 1][MAX_SIDE + 1];
int main() {

Java

import java.io.*;import java.util.StringTokenizer;
public class ForestQueries {	static int N;	static int Q;	static int[][] pfx;	static int[][] arr;	public static void main(String[] args) {		Kattio io = new Kattio();

Python

side_len, query_num = [int(i) for i in input().split()]tree_prefixes = [[0 for _ in range(side_len + 1)] for _ in range(side_len + 1)]for r in range(side_len):	for ci, c in enumerate(input()):		tree = c == '*'		tree_prefixes[r + 1][ci + 1] += (tree_prefixes[r][ci + 1]										 + tree_prefixes[r + 1][ci]										 - tree_prefixes[r][ci]										 + tree)


### Problems

StatusSourceProblem NameDifficultyTags
SilverEasy
Show Tags2D Prefix Sums
Old SilverEasy
Show Tags2D Prefix Sums
SilverHard
Show Tags2D Prefix Sums
GoldHard
Show Tags2D Prefix Sums, Max Subarray Sum
PlatVery Hard
Show Tags2D Prefix Sums

### 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!