Solution: Number of Submatrices That Sum to Target (2024)

This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode's forums.

Leetcode Problem #1074 (Hard): Number of Submatrices That Sum to Target

Description:


(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)

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'.

Examples:

Example 1:
Input:matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output:4
Explanation:The four 1x1 submatrices that only contain 0.
Visual:Solution: Number of Submatrices That Sum to Target (1)
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

Idea:


(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)

This problem is essentially a 2-dimensional version of #560. Subarray Sum Equals K (S.S.E.K). By using a prefix sum on each row or each column, we can compress this problem down to either N^2 iterations of the O(M) SSEK, or M^2 iterations of the O(N) SSEK.

In the SSEK solution, we can find the number of subarrays with the target sum by utilizing a result map (res) to store the different values found as we iterate through the array while keeping a running sum (csum). Just as in the case with a prefix sum array, the sum of a subarray between i and j is equal to the sum of the subarray from 0 to j minus the sum of the subarray from 0 to i-1.

Rather than iteratively checking if sum[0,j] - sum[0,i-1] = T for every pair of i, j values, we can flip it around to sum[0,j] - T = sum[0,i-1] and since every earlier sum value has been stored in res, we can simply perform a lookup on sum[0,j] - T to see if there are any matches.

When extrapolating this solution to our 2-dimensional matrix (M), we will need to first prefix sum the rows or columns, (which we can do in-place to avoid extra space, as we will not need the original values again). Then we should iterate through M again in the opposite order of rows/columns where the prefix sums will allow us to treat a group of columns or rows as if it were a 1-dimensional array and apply the SSEK algorithm.

Implementation:

There are only minor differences in the code of all four languages.

Javascript Code:


(Jump to: Problem Description || Solution Idea)

var numSubmatrixSumTarget = function(M, T) { let xlen = M[0].length, ylen = M.length, ans = 0, res = new Map() for (let i = 0, r = M[0]; i < ylen; r = M[++i]) for (let j = 1; j < xlen; j++) r[j] += r[j-1] for (let j = 0; j < xlen; j++) for (let k = j; k < xlen; k++) { res.clear(), res.set(0,1), csum = 0 for (let i = 0; i < ylen; i++) { csum += M[i][k] - (j ? M[i][j-1] : 0) ans += (res.get(csum - T) || 0) res.set(csum, (res.get(csum) || 0) + 1) } } return ans};

Python Code:


(Jump to: Problem Description || Solution Idea)

class Solution: def numSubmatrixSumTarget(self, M: List[List[int]], T: int) -> int: xlen, ylen, ans, res = len(M[0]), len(M), 0, defaultdict(int) for r in M: for j in range(1, xlen): r[j] += r[j-1] for j in range(xlen): for k in range(j, xlen): res.clear() res[0], csum = 1, 0 for i in range(ylen): csum += M[i][k] - (M[i][j-1] if j else 0) ans += res[csum - T] res[csum] += 1 return ans

Java Code:


(Jump to: Problem Description || Solution Idea)

class Solution { public int numSubmatrixSumTarget(int[][] M, int T) { int xlen = M[0].length, ylen = M.length, ans = 0; Map<Integer, Integer> res = new HashMap<>(); for (int[] r : M) for (int j = 1; j < xlen; j++) r[j] += r[j-1]; for (int j = 0; j < xlen; j++) for (int k = j; k < xlen; k++) { res.clear(); res.put(0,1); int csum = 0; for (int i = 0; i < ylen; i++) { csum += M[i][k] - (j > 0 ? M[i][j-1] : 0); ans += res.getOrDefault(csum - T, 0); res.put(csum, res.getOrDefault(csum, 0) + 1); } } return ans; }}

C++ Code:


(Jump to: Problem Description || Solution Idea)

class Solution {public: int numSubmatrixSumTarget(vector<vector<int>>& M, int T) { int xlen = M[0].size(), ylen = M.size(), ans = 0; unordered_map<int, int> res; for (int i = 0; i < ylen; i++) for (int j = 1; j < xlen; j++) M[i][j] += M[i][j-1]; for (int j = 0; j < xlen; j++) for (int k = j; k < xlen; k++) { res.clear(); res[0] = 1; int csum = 0; for (int i = 0; i < ylen; i++) { csum += M[i][k] - (j ? M[i][j-1] : 0); ans += res.find(csum - T) != res.end() ? res[csum - T] : 0; res[csum]++; } } return ans; }};

Solution: 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).

What is the formula for submatrices? ›

Let us suppose the index of an element be (X, Y) in 0 based indexing, then the number of submatrices (Sx, y) for this element will be given by the formula Sx, y = (X + 1) * (Y + 1) * (N – X) * (N – Y).

How to find the sum of a submatrix? ›

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.

What is a sub-matrix with an example? ›

1.5 Submatrices and Partitioning. Given any matrix A, a submatrix of A is a matrix obtained from A by the removal of any number of rows or columns. (11) A= [ 1 2 3 4 5 6 6 8 9 10 11 12 13 14 15 16 ] B= [ 10 12 14 16 ] and C= [ 2 3 4 ] then B and C are both submatrices of A.

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

= initial_matrix[r0 + i][c0 + j]; In your case this would mean e.g. [1 + i][1 + j] to get the bottom-right submatrix with both i and j counting up from 0 to excluded 2 (i.e. counting 0 and 1).

Does interchanging rows change the determinant? ›

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

How to find principal submatrices? ›

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.

What is the meaning of submatrices? ›

noun. , Mathematics. , plural sub·ma·tri·ces [suhb-, mey, -tri-seez, -, ma, -tri-seez], sub·ma·trix·es. a set of certain rows and columns of a given matrix.

How to get a submatrix? ›

If you wire a 2D array to matrix, submatrix returns a 2D array with the same numeric type as matrix. If you wire matrix but you do not wire the other inputs, submatrix returns matrix. If you do not wire inputs to row 1 and column 1, submatrix starts with the first element of matrix.

What is the formula for summing numbers? ›

The formula to calculate the sum of integers is given as, S = n(a + l)/2, where, S is sum of the consecutive integers n is number of integers, a is first term and l is last term.

How do you solve for the sum? ›

When we add two or more numbers, the result or the answer we get can be defined as the SUM. The numbers that are added are called addends. In the above example, 6 and 4 are addends, and 10 is their sum. In other words, we can say the sum of 8 and 5 is 13 or 8 added to 5 is 13.

How many submatrix are in a matrix? ›

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. This can be written as a recursive formula: f(m, n + 1) = f(m, n) + m(m + 1)(n + 1) 2 .

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 is the difference between a submatrix and a minor? ›

A submatrix of a matrix is obtained by deleting any collection of rows and/or columns. The minors and cofactors of a matrix are found by computing the determinant of certain submatrices. A principal submatrix is a square submatrix obtained by removing certain rows and columns.

How to get submatrix in R? ›

The sub matrices can be accessed by getSM function and can be modifed by modSM function. To transpose a supermatrix, use transp function instead since it preserves the SMdim attributes. To print a super matrix with its submatrices being separated, use Printb function.

What is an idempotent matrix with an example? ›

Idempotent matrix is a square matrix which when multiplied by itself, gives back the same matrix. A matrix M is said to be an idempotent matrix if M2 = M. Further every identity matrix can be termed as an idempotent matrix. The idempotent matrix is a singular matrix and can have non-zero elements.

How to do transpose of a matrix? ›

The transpose of a matrix, designated M ˜ or M T , is obtained by interchanging its rows and columns or, alternatively, by reflecting all the matrix elements through the main diagonal: (9.48) M → M ˜ when m ij → m ji all i , j . (9.49) σ 1 = 0 1 1 0 and σ 3 = 1 0 0 - 1 . (9.50) σ 2 = 0 - i i 0 .

Top Articles
Latest Posts
Article information

Author: Kelle Weber

Last Updated:

Views: 6701

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.