The Indian Engineer

Problem 1074 Number of Submatrices That Sum to Target

Posted on 6 mins

Array Hash-Table Matrix Prefix-Sum

Problem Statement

Link - Problem 1074

Question

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:

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:

Solution

class Solution {
public:
    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
        int numRows = matrix.size();
        int numCols = matrix[0].size();

        vector<vector<int>> prefixSum(numRows + 1, vector<int>(numCols + 1, 0));

        for (int row = 0; row < numRows; ++row) {
            for (int col = 0; col < numCols; ++col) {
                prefixSum[row + 1][col + 1] = prefixSum[row][col + 1] + prefixSum[row + 1][col] - prefixSum[row][col] + matrix[row][col];
            }
        }

        int count = 0;
        for (int row1 = 0; row1 < numRows; ++row1) {
            for (int row2 = row1 + 1; row2 <= numRows; ++row2) {
                unordered_map<int, int> counter;
                counter[0] = 1;
                for (int col = 1; col <= numCols; ++col) {
                    int currSum = prefixSum[row2][col] - prefixSum[row1][col];
                    count += counter[currSum - target];
                    ++counter[currSum];
                }
            }
        }
        return count;
    }
};

Complexity Analysis

| Algorithm                | Time Complexity | Space Complexity |
| ------------------------ | --------------- | ---------------- |
| Hash Map with Prefix Sum | O(n^3 log n)    | O(n)             |

Explanation

Intial Thoughts

To approach this problem, first think about the structure of a matrix and how submatrices are formed. Consider how you can efficiently calculate the sum of each submatrix. Note that the problem statement involves both positive and negative numbers, which can result in both positive and negative sums. Think about how you can keep track of the sums that have been seen so far. It might be useful to use a prefix sum array or a hash map to store intermediate results. Break down the problem into smaller sub-problems, such as calculating the sum of submatrices with a specific row or column range.

Intuitive Analysis

To intuitively solve this problem, think of the prefix sum array as a tool to efficiently calculate the sum of any submatrix. Imagine a sliding window approach where you are moving the top and bottom boundaries of the submatrix, and for each position, you are calculating the sum of the submatrix. Use a hash map to store the frequency of each sum that has been seen so far. The key insight is that the number of submatrices that sum to the target is equal to the number of times the target minus the current sum is seen in the hash map. By using this approach, you can avoid recalculating the sum of submatrices and reduce the time complexity.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Hard difficulty.

Hints

Using a 2D prefix sum, we can query the sum of any submatrix in O(1) time. Now for each (r1, r2), we can find the largest sum of a submatrix that uses every row in [r1, r2] in linear time using a sliding window.


Similar Questions:

Title URL Difficulty
Disconnect Path in a Binary Matrix by at Most One Flip https://leetcode.com/problems/disconnect-path-in-a-binary-matrix-by-at-most-one-flip Medium