Number of Submatrices That Sum to Target (2024)

Given a matrix and a target, return the number of non-empty submatrices that sum to target.

A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.

Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.

Example 1:

Number of Submatrices That Sum to Target (2)
Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.

Example 2:

Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.

Example 3:

Input: matrix = [[904]], target = 0
Output: 0

Constraints:

  • 1 <= matrix.length <= 100
  • 1 <= matrix[0].length <= 100
  • -1000 <= matrix[i] <= 1000
  • -10^8 <= target <= 10^8
  1. For a matrix, what is the prefix sum ?
  2. sum[x] [y] is the sum of submatrix
  3. (The upper left corner is matrix[0] [0], the lower right corner is matrix[x] [y])
Number of Submatrices That Sum to Target (3)
  1. How to calculate the sum of all submatrices whose upper left corners are matrix[0] [0]
  2. Step 1. Calculate the prefix sum of each line.
Number of Submatrices That Sum to Target (4)
// Like the one-dimensional prefix sum, 
// in order to prevent index out of range and facilitate calculations,
// we add an extra column with all 0s at the forefront.
int line = matrix.length;
int column = matrix[0].length + 1;
int[][] sum = new int[line][column]; // Initialization default is all 0
for (int l = 0; l < sum.length; l++){ // start from the second column
for (int c = 1; c < sum[0].length; c++){
sum[l][c] = sum[l][c - 1] + matrix[l][c - 1]; // "c - 1",because of an extra column.
}
}
Number of Submatrices That Sum to Target (5)
  1. Step 2. Using the prefix sum of each line to calculate the sum of submatrix.
Number of Submatrices That Sum to Target (6)
  • sum[1][2] = sum[1][2] + sum[0][2]; // green + orang
  • sum[2][2] = sum[2][2] + sum[1][2] + sum[0][2]; // blue + green + orange
  1. So, to caculate any sum of submatrices whose upper left corner are matrix[0] [0].
int sumOfSubMatrix = 0; 
for(int l = 0; l < line; l++){
sumOfSubMatrix += sum[l][column]; // one of submatrices
}
  1. How to find all submatrices ?
  2. Any submatrix needs any two rows and any two columns to form, that is to say, four variables and four nested loops are required.
// Use double nested "for" loop to select any two columns 
for (int start = 0; start < column; start++){
for (int end = start + 1; end < column; end++ ){
// ... // Then Use double nested "for" loop to select any two lines
}
}
  1. Convert 2D to 1D
  2. Step 1 : Use the prefix sum of each row to calculate the matrix sum between the “start” column and “end” column.
Number of Submatrices That Sum to Target (7)
  1. Step 2 : Rotate it 90 degrees to the left, it can be regarded as a one-dimensional array.
Number of Submatrices That Sum to Target (8)
  1. Then the problem is transformed into how many sub-arrays whose sum == target ?
  2. Step 3 : In the same way, we can use hashmap to optimize the double nested loop for any two lines, and only need one loop
int sumOfSubMatrix = 0; 
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, 1);
for(int l = 0; l < line; l++){
// prefix sum
sumOfSubMatrix += sum[l][end] - sum[l][start];
if (map.containsKey(sumOfSubMatrix - target))
count += map.get(sumOfSubMatrix - target);
map.put(sumOfSubMatrix, map.getOrDefault(sumOfSubMatrix, 0) + 1);
  1. What’s the meaning of this sentence ?
  • “Any submatrix needs any two rows and any two columns to form, that is to say, four variables and four nested loops are required.”
  • eg. |0| is the submatrix I want to find, whose index is [0][0]
    In the “sum”, the column 1 corresponds to column 0 in “matrix”. SO we bound the area like this
Number of Submatrices That Sum to Target (9)

Since we have done prefix sum for every line, we need to do sum[line][end_column] — sum[line][start_column], and in this case elements in start_column is all 0, when we subtract sum[line][0], It actually did nothing.

Also, since “end_cloumn” starts from “end_cloumn = start_column + 1”, it is impossible to treat the first column of “sum” as part of our result.

Number of Submatrices That Sum to Target (10)
class Solution {
public int numSubmatrixSumTarget(int[][] matrix, int target) {
int count = 0;
int row = matrix.length;
int column = matrix[0].length + 1;
int[][] sum = new int[row][column];

for (int i = 0; i < sum.length; i++){
for (int j = 1; j < sum[0].length; j++){
sum[i][j] = sum[i][j - 1] + matrix[i][j - 1];
}
}

for (int start = 0; start < column; start++){
for (int end = start + 1; end < column; end++ ){

int sumOfSubMatrix = 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, 1);
for(int l = 0; l < row; l++){
sumOfSubMatrix += sum[l][end] - sum[l][start];
if (map.containsKey(sumOfSubMatrix - target))
count += map.get(sumOfSubMatrix - target);
map.put(sumOfSubMatrix, map.getOrDefault(sumOfSubMatrix, 0) + 1);

}
}
}

return count;

}
}

If you Liked My Explanation

You can connect with me on Linkedin for more Reads like this!

Here is my linkedin Profile https://www.linkedin.com/in/roshan-jha-20m10/

Number of Submatrices That Sum to Target (2024)

FAQs

How to find the number of submatrices? ›

If you have an m×n matrix, and you want to find the number of p×q submatrices found within it, then you need to choose p rows from the m available, and q columns from the n available. The total number of such is (mp)(nq).

How many submatrices does a matrix have? ›

There are m(m + 1) 2 submatrices of width 1 (this is anologous to substrings). For each such matrix, in corresponding rows, there are n + 1 submatrices (exactly one of width 1,2,3··· ,n + 1). Hence, in total there are m(m + 1)(n + 1) 2 submatrices which are newly added.

What is a sub matrix in math? ›

A submatrix of a matrix A is a matrix obtained from A by removing any number of rows or columns from A. From: Linear Algebra (Third Edition), 2014.

How to find the submatrix of a matrix in C? ›

Obtaining a submatrix from a squared matrix in C
  1. R is the number of rows of the initial matrix (so in this case R=3 )
  2. C is the number of columns of the initial matrix (so in this case C=3 )
  3. r is the number of rows of the submatrix that i want to obtain (so in this case r=2 )
Dec 12, 2022

Does interchanging rows change the determinant? ›

Property 2: If any two rows (or columns) of a determinant are interchanged, then sign of determinant changes.

What are the leading principal submatrices of a matrix? ›

The principal submatrices of a matrix are the matrix itself and those submatrices obtained from it by repeatedly striking out a row and the column of the same index. The leading principal sub matrices are Lhose obtained by striking out exactly one row and its cOlTesponding column.

How do you find all the submatrix of a matrix? ›

The number of submatrices

There are (n – k + 1) sequences of consecutive rows of length k, such as 1:k, 2:(k+1), and so forth. Similarly, there are (m – k + 1) sequences of consecutive columns of length k. So the following SAS/IML function counts the number of submatrices of order k.

How do you find the number of matrices? ›

Detailed Solution
  1. The total number of ways in which n objects can be arranged at r places, without repetition, is n × (n - 1) × (n - 2) × ... × 2 × 1 = n!.
  2. The total number of ways in which n objects can be arranged at r places, with repetition, is n × n × n × ... × n (r times) = nr.
May 15, 2024

What are the 4 types of matrices? ›

The various types of matrices are row matrix, column matrix, null matrix, square matrix, diagonal matrix, upper triangular matrix, lower triangular matrix, symmetric matrix, and antisymmetric matrix.

How to denote a submatrix? ›

In various programming languages, notably MATLAB, and in numerical linear algebra, a colon notation is used to denote submatrices consisting of contiguous rows and columns. Here are some examples of using the colon notation to extract submatrices in MATLAB.

What are sub numbers in math? ›

A subscript in math is a number or variable that is written in small script at the bottom right corner of another number or variable. For example, in the term , is a subscript. Another example of a subscript is the 3 in the term .

How many eigen values can a matrix have? ›

Since a polynomial of degree n has at most n roots, the matrix has as most n eigenvalues.

How many inverses can a matrix have? ›

A matrix A can have at most one inverse. The inverse of an invertible matrix is denoted A-1. Also, when a matrix is invertible, so is its inverse, and its inverse's inverse is itself, (A-1)-1 = A. Thus, there is at most one inverse.

Is a matrix a submatrix of itself? ›

Since the matrix is a 2 × 2 square matrix, the largest possible square submatrix is the original matrix itself.

How many 3x3 matrices are there? ›

According to the problem, each entry of a 3x3 matrix can be filled up by two ways, either by 0 or by 2 . And there are 9 entries in a 3x3 matrix, hence the total no. of possible 3x3 matrices with entries 0 or 2 = 2^(9) = 512 .

Top Articles
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 6703

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.