Given a matrix of size M x N, there are large number of queries to find submatrix sums. Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find out.
How to preprocess the matrix so that submatrix sum queries can be performed in O(1) time.
Example :
tli : Row number of top left of query submatrix
tlj : Column number of top left of query submatrix
rbi : Row number of bottom right of query submatrix
rbj : Column number of bottom right of query submatrix
Input: mat[M][N] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
Query1: tli = 0, tlj = 0, rbi = 1, rbj = 1
Query2: tli = 2, tlj = 2, rbi = 3, rbj = 4
Query3: tli = 1, tlj = 2, rbi = 3, rbj = 3;
Output:
Query1: 11 // Sum between (0, 0) and (1, 1)
Query2: 38 // Sum between (2, 2) and (3, 4)
Query3: 38 // Sum between (1, 2) and (3, 3)
We strongly recommend you to minimize your browser and try this yourself first.
The idea is to first create an auxiliary matrix aux[M][N] such that aux[i][j] stores sum of elements in submatrix from (0,0) to (i,j). Once aux[][] is constructed, we can compute sum of submatrix between (tli, tlj) and (rbi, rbj) in O(1) time. We need to consider aux[rbi][rbj] and subtract all unnecessary elements. Below is complete expression to compute submatrix sum in O(1) time.
Sum between (tli, tlj) and (rbi, rbj) is,
aux[rbi][rbj] - aux[tli-1][rbj] -
aux[rbi][tlj-1] + aux[tli-1][tlj-1]
The submatrix aux[tli-1][tlj-1] is added because
elements of it are subtracted twice.
Illustration:
mat[M][N] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
We first preprocess the matrix and build
following aux[M][N]
aux[M][N] = {1, 3, 6, 10, 16}
{6, 11, 22, 27, 35},
{10, 21, 39, 49, 62},
{12, 27, 53, 72, 89} }
Query : tli = 2, tlj = 2, rbi = 3, rbj = 4
Sum between (2, 2) and (3, 4) = 89 - 35 - 27 + 11
= 38
How to build aux[M][N]?
1. Copy first row of mat[][] to aux[][]
2. Do column wise sum of the matrix and store it.
3. Do the row wise sum of updated matrix aux[][] in step 2.
Below is the program based on above idea.
C++
// C++ program to compute submatrix query sum in O(1)
// time
#include<iostream>
using namespace std;
#define M 4
#define N 5
// Function to preprocess input mat[M][N]. This function
// mainly fills aux[M][N] such that aux[i][j] stores sum
// of elements from (0,0) to (i,j)
int preProcess(int mat[M][N], int aux[M][N])
{
// Copy first row of mat[][] to aux[][]
for (int i=0; i<N; i++)
aux[0][i] = mat[0][i];
// Do column wise sum
for (int i=1; i<M; i++)
for (int j=0; j<N; j++)
aux[i][j] = mat[i][j] + aux[i-1][j];
// Do row wise sum
for (int i=0; i<M; i++)
for (int j=1; j<N; j++)
aux[i][j] += aux[i][j-1];
}
// A O(1) time function to compute sum of submatrix
// between (tli, tlj) and (rbi, rbj) using aux[][]
// which is built by the preprocess function
int sumQuery(int aux[M][N], int tli, int tlj, int rbi,
int rbj)
{
// result is now sum of elements between (0, 0) and
// (rbi, rbj)
int res = aux[rbi][rbj];
// Remove elements between (0, 0) and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1][rbj];
// Remove elements between (0, 0) and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi][tlj-1];
// Add aux[tli-1][tlj-1] as elements between (0, 0)
// and (tli-1, tlj-1) are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1][tlj-1];
return res;
}
// Driver program
int main()
{
int mat[M][N] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4} };
int aux[M][N];
preProcess(mat, aux);
int tli = 2, tlj = 2, rbi = 3, rbj = 4;
cout << "\nQuery1: " << sumQuery(aux, tli, tlj, rbi, rbj);
tli = 0, tlj = 0, rbi = 1, rbj = 1;
cout << "\nQuery2: " << sumQuery(aux, tli, tlj, rbi, rbj);
tli = 1, tlj = 2, rbi = 3, rbj = 3;
cout << "\nQuery3: " << sumQuery(aux, tli, tlj, rbi, rbj);
return 0;
}
Java
// Java program to compute submatrix query
// sum in O(1) time
import java.util.*;
import java.io.*;
class GFG {
static final int M = 4;
static final int N = 5;
// Function to preprocess input mat[M][N].
// This function mainly fills aux[M][N]
// such that aux[i][j] stores sum of
// elements from (0,0) to (i,j)
static int preProcess(int mat[][], int aux[][])
{
// Copy first row of mat[][] to aux[][]
for (int i = 0; i < N; i++)
aux[0][i] = mat[0][i];
// Do column wise sum
for (int i = 1; i < M; i++)
for (int j = 0; j < N; j++)
aux[i][j] = mat[i][j] +
aux[i-1][j];
// Do row wise sum
for (int i = 0; i < M; i++)
for (int j = 1; j < N; j++)
aux[i][j] += aux[i][j-1];
return 0;
}
// A O(1) time function to compute sum
// of submatrix between (tli, tlj) and
// (rbi, rbj) using aux[][] which is
// built by the preprocess function
static int sumQuery(int aux[][], int tli,
int tlj, int rbi, int rbj)
{
// result is now sum of elements
// between (0, 0) and (rbi, rbj)
int res = aux[rbi][rbj];
// Remove elements between (0, 0)
// and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1][rbj];
// Remove elements between (0, 0)
// and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi][tlj-1];
// Add aux[tli-1][tlj-1] as elements
// between (0, 0) and (tli-1, tlj-1)
// are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1][tlj-1];
return res;
}
// Driver code
public static void main (String[] args)
{
int mat[][] = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4}};
int aux[][] = new int[M][N];
preProcess(mat, aux);
int tli = 2, tlj = 2, rbi = 3, rbj = 4;
System.out.print("\nQuery1: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
tli = 0; tlj = 0; rbi = 1; rbj = 1;
System.out.print("\nQuery2: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
tli = 1; tlj = 2; rbi = 3; rbj = 3;
System.out.print("\nQuery3: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python 3 program to compute submatrix
# query sum in O(1) time
M = 4
N = 5
# Function to preprocess input mat[M][N].
# This function mainly fills aux[M][N]
# such that aux[i][j] stores sum
# of elements from (0,0) to (i,j)
def preProcess(mat, aux):
# Copy first row of mat[][] to aux[][]
for i in range(0, N, 1):
aux[0][i] = mat[0][i]
# Do column wise sum
for i in range(1, M, 1):
for j in range(0, N, 1):
aux[i][j] = mat[i][j] + aux[i - 1][j]
# Do row wise sum
for i in range(0, M, 1):
for j in range(1, N, 1):
aux[i][j] += aux[i][j - 1]
# A O(1) time function to compute sum of submatrix
# between (tli, tlj) and (rbi, rbj) using aux[][]
# which is built by the preprocess function
def sumQuery(aux, tli, tlj, rbi, rbj):
# result is now sum of elements
# between (0, 0) and (rbi, rbj)
res = aux[rbi][rbj]
# Remove elements between (0, 0)
# and (tli-1, rbj)
if (tli > 0):
res = res - aux[tli - 1][rbj]
# Remove elements between (0, 0)
# and (rbi, tlj-1)
if (tlj > 0):
res = res - aux[rbi][tlj - 1]
# Add aux[tli-1][tlj-1] as elements
# between (0, 0) and (tli-1, tlj-1)
# are subtracted twice
if (tli > 0 and tlj > 0):
res = res + aux[tli - 1][tlj - 1]
return res
# Driver Code
if __name__ == '__main__':
mat = [[1, 2, 3, 4, 6],
[5, 3, 8, 1, 2],
[4, 6, 7, 5, 5],
[2, 4, 8, 9, 4]]
aux = [[0 for i in range(N)]
for j in range(M)]
preProcess(mat, aux)
tli = 2
tlj = 2
rbi = 3
rbj = 4
print("Query1:", sumQuery(aux, tli, tlj, rbi, rbj))
tli = 0
tlj = 0
rbi = 1
rbj = 1
print("Query2:", sumQuery(aux, tli, tlj, rbi, rbj))
tli = 1
tlj = 2
rbi = 3
rbj = 3
print("Query3:", sumQuery(aux, tli, tlj, rbi, rbj))
# This code is contributed by
# Shashank_Sharma
C#
// C# program to compute submatrix
// query sum in O(1) time
using System;
class GFG
{
static int M = 4;
static int N = 5;
// Function to preprocess input mat[M][N].
// This function mainly fills aux[M][N]
// such that aux[i][j] stores sum of
// elements from (0,0) to (i,j)
static int preProcess(int [,]mat, int [,]aux)
{
// Copy first row of mat[][] to aux[][]
for (int i = 0; i < N; i++)
aux[0,i] = mat[0,i];
// Do column wise sum
for (int i = 1; i < M; i++)
for (int j = 0; j < N; j++)
aux[i,j] = mat[i,j] + aux[i-1,j];
// Do row wise sum
for (int i = 0; i < M; i++)
for (int j = 1; j < N; j++)
aux[i,j] += aux[i,j-1];
return 0;
}
// A O(1) time function to compute sum
// of submatrix between (tli, tlj) and
// (rbi, rbj) using aux[][] which is
// built by the preprocess function
static int sumQuery(int [,]aux, int tli,
int tlj, int rbi, int rbj)
{
// result is now sum of elements
// between (0, 0) and (rbi, rbj)
int res = aux[rbi,rbj];
// Remove elements between (0, 0)
// and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1,rbj];
// Remove elements between (0, 0)
// and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi,tlj-1];
// Add aux[tli-1][tlj-1] as elements
// between (0, 0) and (tli-1, tlj-1)
// are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1,tlj-1];
return res;
}
// Driver code
public static void Main ()
{
int [,]mat = {{1, 2, 3, 4, 6},
{5, 3, 8, 1, 2},
{4, 6, 7, 5, 5},
{2, 4, 8, 9, 4}};
int [,]aux = new int[M,N];
preProcess(mat, aux);
int tli = 2, tlj = 2, rbi = 3, rbj = 4;
Console.Write("\nQuery1: " +
sumQuery(aux, tli, tlj, rbi, rbj));
tli = 0; tlj = 0; rbi = 1; rbj = 1;
Console.Write("\nQuery2: " +
sumQuery(aux, tli, tlj, rbi, rbj));
tli = 1; tlj = 2; rbi = 3; rbj = 3;
Console.Write("\nQuery3: " +
sumQuery(aux, tli, tlj, rbi, rbj));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to compute submatrix
// query sum in O(1) time
// Function to preprocess input mat[M][N].
// This function mainly fills aux[M][N]
// such that aux[i][j] stores sum
// of elements from (0,0) to (i,j)
function preProcess(&$mat, &$aux)
{
$M = 4;
$N = 5;
// Copy first row of mat[][] to aux[][]
for ($i = 0; $i < $N; $i++)
$aux[0][$i] = $mat[0][$i];
// Do column wise sum
for ($i = 1; $i < $M; $i++)
for ($j = 0; $j < $N; $j++)
$aux[$i][$j] = $mat[$i][$j] +
$aux[$i - 1][$j];
// Do row wise sum
for ($i = 0; $i < $M; $i++)
for ($j = 1; $j < $N; $j++)
$aux[$i][$j] += $aux[$i][$j - 1];
}
// A O(1) time function to compute sum of
// submatrix between (tli, tlj) and
// (rbi, rbj) using aux[][] which is built
// by the preprocess function
function sumQuery(&$aux, $tli, $tlj, $rbi,$rbj)
{
// result is now sum of elements
// between (0, 0) and (rbi, rbj)
$res = $aux[$rbi][$rbj];
// Remove elements between (0, 0)
// and (tli-1, rbj)
if ($tli > 0)
$res = $res - $aux[$tli - 1][$rbj];
// Remove elements between (0, 0)
// and (rbi, tlj-1)
if ($tlj > 0)
$res = $res - $aux[$rbi][$tlj - 1];
// Add aux[tli-1][tlj-1] as elements between (0, 0)
// and (tli-1, tlj-1) are subtracted twice
if ($tli > 0 && $tlj > 0)
$res = $res + $aux[$tli - 1][$tlj - 1];
return $res;
}
// Driver Code
$mat = array(array(1, 2, 3, 4, 6),
array(5, 3, 8, 1, 2),
array(4, 6, 7, 5, 5),
array(2, 4, 8, 9, 4));
preProcess($mat, $aux);
$tli = 2;
$tlj = 2;
$rbi = 3;
$rbj = 4;
echo ("Query1: ");
echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj));
$tli = 0;
$tlj = 0;
$rbi = 1;
$rbj = 1;
echo ("\nQuery2: ");
echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj));
$tli = 1;
$tlj = 2;
$rbi = 3;
$rbj = 3;
echo ("\nQuery3: ");
echo(sumQuery($aux, $tli, $tlj, $rbi, $rbj));
// This code is contributed by Shivi_Aggarwal
?>
JavaScript
<script>
// Javascript program to compute submatrix query
// sum in O(1) time
var M = 4;
var N = 5;
// Function to preprocess input mat[M][N].
// This function mainly fills aux[M][N]
// such that aux[i][j] stores sum of
// elements from (0,0) to (i,j)
function preProcess(mat, aux)
{
// Copy first row of mat[][] to aux[][]
for (var i = 0; i < N; i++)
aux[0,i] = mat[0,i];
// Do column wise sum
for (var i = 1; i < M; i++)
for (var j = 0; j < N; j++)
aux[i][j] = mat[i][j] +
aux[i-1][j];
// Do row wise sum
for (var i = 0; i < M; i++)
for (var j = 1; j < N; j++)
aux[i][j] += aux[i][j-1];
return 0;
}
// A O(1) time function to compute sum
// of submatrix between (tli, tlj) and
// (rbi, rbj) using aux[][] which is
// built by the preprocess function
function sumQuery( aux, tli, tlj, rbi, rbj)
{
// result is now sum of elements
// between (0, 0) and (rbi, rbj)
var res = aux[rbi][rbj];
// Remove elements between (0, 0)
// and (tli-1, rbj)
if (tli > 0)
res = res - aux[tli-1][rbj];
// Remove elements between (0, 0)
// and (rbi, tlj-1)
if (tlj > 0)
res = res - aux[rbi][tlj-1];
// Add aux[tli-1][tlj-1] as elements
// between (0, 0) and (tli-1, tlj-1)
// are subtracted twice
if (tli > 0 && tlj > 0)
res = res + aux[tli-1][tlj-1];
return res;
}
// Driver code
var mat= [[1, 2, 3, 4, 6],
[5, 3, 8, 1, 2],
[4, 6, 7, 5, 5],
[2, 4, 8, 9, 4]];
var aux = new Array(M,N);
preProcess(mat, aux);
var tli = 2, tlj = 2, rbi = 3, rbj = 4;
document.write("\nQuery1: "
+ sumQuery(aux, tli, tlj, rbi, rbj)+"<br>");
tli = 0; tlj = 0; rbi = 1; rbj = 1;
document.write("\nQuery2: "
+ sumQuery(aux, tli, tlj, rbi, rbj)+"<br>");
tli = 1; tlj = 2; rbi = 3; rbj = 3;
document.write("\nQuery3: "
+ sumQuery(aux, tli, tlj, rbi, rbj));
}
}
// This code is contributed by shivanisinghss2110
</script>
Output
Query1: 38
Query2: 11
Query3: 38
Time complexity: O(M x N).
Auxiliary Space: O(M x N), since M x N extra space has been taken.
Source: https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-set-241-1-5-years-experience/
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem