(Translated by https://www.hiragana.jp/)
Prefix Sum of Matrix (Or 2D Array) - GeeksforGeeks
Open In App

Prefix Sum of Matrix (Or 2D Array)

Last Updated : 25 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a 2D integer matrix mat[][]and a list of queries queries[][], the objective is to compute the sum of elements within a specific submatrix of the given matrix for each query.

Each query is defined by four integers [r1, c1, r2, c2].

  • r1, c1: the top-left coordinate of the submatrix
  • r2, c2: the bottom-right coordinate of the submatrix

All coordinates are inclusive, meaning the submatrix includes the elements at both (r1, c1) and (r2, c2).

Examples:

Input: mat[][] = [[1, 2, 3], queries[][] = [[0, 0, 1, 1], [1, 0, 2, 2]]
[1, 1, 0],
[4, 2, 2]]
Output: [5, 10]
Explanation:
Query 1 selects submatrix [[1, 2], [1, 1]] → sum = 5.
Query 2 selects submatrix [[1, 1, 0], [4, 2, 2]] → sum = 10.

Input: mat[][] = [[1, 1, 1], queries[][] = [[1, 1, 2, 2], [0, 0, 2, 2], [0, 2, 2, 2]]
[1, 1, 1],
[1, 1, 1]]
Output: [4, 9, 3]
Explanation:
Query 1 selects submatrix [[1, 1], [1, 1]] → sum = 4.
Query 2 selects submatrix [[1, 1, 1], [1, 1, 1], [1, 1, 1]] → sum = 9.
Query 3 selects submatrix [[1], [1], [1]] → sum = 3.

 [Naive Approach] Brute Force Summation - O(n × m × q) Time and O(1) Space

For each query, traverse the submatrix defined by its corners and accumulate the sum of all elements inside it.
This is done by nested loops over the specified row and column ranges.

C++
Java Python C# JavaScript

Output
5 10 

[Approach] 2D Prefix Sum with Inclusion-Exclusion - O(n × m + q) Time and O(n × m) Space

The idea is to preprocess the matrix using a separate 2D prefix sum matrix pre[][] with 1-based indexing, where each cell stores the sum of the rectangle from the top-left corner to that cell. This allows us to compute the sum of any submatrix in constant time using the inclusion-exclusion principle.
For a query (r1, c1, r2, c2), the formula is: sum = total - top - left + overlap

total => pre[r2][c2]
top => pre[r1-1][c2]
left => pre[r2][c1-1]
overlap => pre[r1][c1]

C++
Java Python C# JavaScript

Output
5 10 

[Efficient Approach] In-Place 2D Prefix Sum with Inclusion-Exclusion - O(n × m + q) Time and O(1) Space

This approach uses the 2D prefix sum technique to efficiently compute the sum of elements in any submatrix. The matrix is first preprocessed by calculating cumulative sums row-wise and then column-wise, so that each cell mat[i][j] holds the sum of the rectangle from the top-left (0,0) to (i, j).

For each query defined by (r1, c1) to (r2, c2), the submatrix sum is calculated in constant time using the inclusion-exclusion formula:
sum = mat[r2][c2] - mat[r2][c1 - 1] - mat[r1 - 1][c2] + mat[r1 - 1][c1 - 1]

C++
Java Python C# JavaScript

Output
5 10 

Next Article

Similar Reads