
Problem Statement
This challenge involves identifying and counting submatrices within a given matrix that, when summed, equal a specified target value. A submatrix is defined by its boundaries (x1, y1, x2, y2)
, where x1
to x2
specifies the row boundaries and y1
to y2
specifies the column boundaries. The problem uniquely defines each submatrix not only by size but also by its position, meaning that two submatrices that differ in any of their boundary coordinates are considered different even if they are of the same dimension and contents elsewhere.
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.
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][j] <= 1000
-10^8 <= target <= 10^8
Approach and Intuition
To solve the problem, we need to focus on two main aspects:
- Efficiently calculating the sums of potential submatrices within the given matrix
- Ensuring that our method can operate within the constraints to handle potentially large matrices in feasible time
The examples given illustrate the variety of matrix configurations and target scenarios we might encounter:
- Example 1: Inputs include a matrix of dimensions 3x3 with a target of 0. The output suggests that four 1x1 submatrices add up to the target. These submatrices are identified by the individual '0' values in the matrix.
- Example 2: A 2x2 matrix with a target of 0. Here, a total of 5 submatrices sum to the target, comprising both small (1x2 and 2x1) and the entire matrix (2x2). The presence of both positive and negative numbers offsets the sums beautifully to meet the target across different submatrix sizes.
- Example 3: This involves a simple 1x1 matrix where no submatrix can sum to the non-zero target, resulting in an output of 0.
The approach might involve using some form of cumulative or prefix sum technique for efficient submatrix sum calculation, complemented perhaps by a hashmap for directly accessing count of submatrix sums, similar to handling two-sum problems but extended to matrix subregions. The main computational challenge is the nested nature of submatrices which calls for a careful balance between exhaustive search and efficient sum calculation.
Lastly, observing the constraints:
- Matrix dimensions can go up to 100x100, leading to potentially 10,000 cells.
- Each cell’s values range significantly, and the target can be exceedingly large or small. This implies both spatial considerations for storing intermediate sums and careful numerical operations to handle the extensive range of values and outputs.
Solutions
- Java
class Solution {
public int countSubmatricesWithSum(int[][] grid, int goal) {
int rows = grid.length, cols = grid[0].length;
int[][] prefixSum = new int[rows + 1][cols + 1];
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= cols; ++j) {
prefixSum[i][j] = prefixSum[i - 1][j] + prefixSum[i][j - 1] - prefixSum[i - 1][j - 1] + grid[i - 1][j - 1];
}
}
int result = 0, sum;
Map<Integer, Integer> countMap = new HashMap<>();
for (int colStart = 1; colStart <= cols; ++colStart) {
for (int colEnd = colStart; colEnd <= cols; ++colEnd) {
countMap.clear();
countMap.put(0, 1);
for (int r = 1; r <= rows; ++r) {
sum = prefixSum[r][colEnd] - prefixSum[r][colStart - 1];
result += countMap.getOrDefault(sum - goal, 0);
countMap.put(sum, countMap.getOrDefault(sum, 0) + 1);
}
}
}
return result;
}
}
The provided Java solution tackles the problem of counting the number of submatrices within a given matrix that sum up to a specified target. This solution utilizes an efficient approach by leveraging a prefix sum array combined with hash mapping to streamline the calculation of submatrix sums.
- Firstly, a
prefixSum
2D array is constructed for the inputgrid
to obtain the cumulative sum up to any (i, j) point in constant time. This facilitates the rapid calculation of any submatrix sum. - The algorithm iterates through all possible pairs of starting and ending columns. For each pair of columns, it resets and uses a
HashMap
(referred to ascountMap
in the code) to track the frequency of cumulative row sums encountered thus far. - For every row, the difference between the current row's cumulative sum at
colEnd
andcolStart-1
is calculated to determine the cumulative sum of the submatrix bounded by these columns. - Using
countMap
, the algorithm checks how often the sum of the current row and the previous rows equalssum - goal
. If such a sum has been encountered before, it indicates that a submatrix ending at the current row and within the column bounds sums to the target, and the count of such submatrices is incremented accordingly. - This approach's efficiency is derived from reducing the problem complexity by fixing column bounds and sequentially accumulating and checking row sums.
In practice, ensure to consider edge cases such as empty grids or grids with non-uniform row/column lengths which might not fit this specific implementation strategy directly. By using both spatial (prefix sum) and temporal (hash map frequency counts) optimization, the solution achieves significant efficiency suitable for large matrices.
- Python
from collections import defaultdict
class Solution:
def numberOfSubmatricesWithSum(self, mat: List[List[int]], goal: int) -> int:
rows, cols = len(mat), len(mat[0])
# Calculate 2D prefix sums to help with submatrix sums
prefix_sum = [[0] * (cols + 1) for _ in range(rows + 1)]
for i in range(1, rows + 1):
for j in range(1, cols + 1):
prefix_sum[i][j] = prefix_sum[i - 1][j] + prefix_sum[i][j - 1] - prefix_sum[i - 1][j - 1] + mat[i - 1][j - 1]
total_count = 0
# Consider all possible column pairs and count submatrices with target sum using hashmap
for start_col in range(1, cols + 1):
for end_col in range(start_col, cols + 1):
sums = defaultdict(int)
sums[0] = 1
for row in range(1, rows + 1):
# Compute the current prefix sum for the fixed columns
current_pref = prefix_sum[row][end_col] - prefix_sum[row][start_col - 1]
# Count submatrices that reach the goal
total_count += sums[current_pref - goal]
# Store the current prefix sum in the hashmap
sums[current_pref] += 1
return total_count
To solve the problem of counting the number of submatrices with a sum equal to a specific target within a 2D matrix using Python, follow the approach outlined below:
Calculate the prefix sums for the matrix. This helps in quickly calculating the sum of any submatrix. Initialize a 2D list
prefix_sum
where the entry ati
,j
is the sum of the submatrix from the top-left corner to the positioni-1
,j-1
in the original matrix.Utilize a hash map for optimization. As we iterate through every possible pair of columns, we use the hashmap
sums
to keep track of the various sums encountered so far across the rows. The key idea is to store how often each sum appears up to the current row. This allows you to quickly determine how many times you've seen the current submatrix sum minus the goal. This difference gives the count of submatrices ending at the current row that add up to the target sum.
Follow this methodology to implement the solution:
Compute 2D prefix sums for the matrix. For each cell in the matrix, compute the cumulative sums using both top and left cells, subtracting the overlap to avoid double counting.
Iterate through all pairs of columns. For each pair, reset your sums hash map, setting the count for a sum of
0
to1
to account for perfect matches from the start of the matrix.As you iterate through each row, compute the submatrix sum from the start row to the current row for the column pair.
Check how many times the current sum minus the goal sum has been encountered (indicative of submatrices that sum up to the goal from previous rows).
Update the hashmap with the current sum for updating future iterations.
This approach highlights effective use of both prefix sums and hashmaps to solve a potentially computationally expensive problem of finding submatrix sums efficiently.
No comments yet.