← Home

1074. Number of Submatrices That Sum to Target

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
107

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1074. Number of Submatrices That Sum to Target, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, sliding window, prefix sums.

The notes already sitting in the source point us in the right direction:

  • DP
  • TLE

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are numSubmatrixSumTarget, subarraySum, row.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N^3), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//DP
02//TLE
03class Solution {
04public:
05    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
06        int m = matrix.size(), n = matrix[0].size();
07        vector<vector<int>> dp(m, vector<int>(n, 0));
08        int ans = 0;
09        
10        for(int i = 0; i < m; i++){
11            for(int j = 0; j < n; j++){
12                int left = (j-1) >= 0 ? dp[i][j-1] : 0;
13                int top = (i-1) >= 0 ? dp[i-1][j] : 0;
14                int lefttop = ((i-1) >= 0 && (j-1) >= 0) ? dp[i-1][j-1] : 0;
15                dp[i][j] = matrix[i][j] + left + top - lefttop;
16            }
17        }
18        
19        //coords acts as helper to generate the range of submatrix
20        // vector<pair<int, int>> coords;
21        vector<pair<int, int>> coords((1+max(m,n))*(max(m,n))/2);
22        
23        int tmp = 0;
24        for(int high = 0; high < max(m, n); high++){
25            for(int low = 0; low <= high; low++){
26                coords[tmp++] = make_pair(low, high);
27                // cout << low << "-" << high << endl;
28            }
29        }
30        
31        int mtri = (1+m)*m/2, ntri = (1+n)*n/2;
32        
33        // cout << "mtri: " << mtri << ", ntri: " << ntri << endl;
34        
35        
36        //generate submatrices and check their sum
37        for(int i = 0; i < mtri; i++){
38            for(int j = 0; j < ntri; j++){
39                int ilow = coords[i].first, ihigh = coords[i].second;
40                int jlow = coords[j].first, jhigh = coords[j].second;
41                // cout << "(" << i << "," << j << "): " << "[" << ilow << "," << ihigh << "] - [" << jlow << "," << jhigh << "]" << endl;
42                int left = (jlow-1) >= 0 ? dp[ihigh][jlow-1] : 0;
43                int top = (ilow-1) >= 0 ? dp[ilow-1][jhigh] : 0;
44                int lefttop = ((ilow-1) >= 0 && (jlow-1) >= 0) ? dp[ilow-1][jlow-1] : 0;
45                int submatrix = dp[ihigh][jhigh] - left - top + lefttop;
46                if(submatrix == target){
47                    ans++;
48                }
49            }
50        }
51        
52        return ans;
53    }
54};
55
56//https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/303750/JavaC%2B%2BPython-Find-the-Subarray-with-Target-Sum
57//time: O(N^3), space: O(N)
58class Solution {
59public:
60    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
61        int ans = 0, m = matrix.size(), n = matrix[0].size();
62        
63        //convert A to prefix sum of each row
64        for(int i = 0; i < m; i++){
65            for(int j = 1; j < n; j++){
66                matrix[i][j] += matrix[i][j-1];
67            }
68        }
69        
70        for(int col_low = 0; col_low < n; col_low++){
71            for(int col_high = col_low; col_high < n; col_high++){
72                unordered_map<int, int> counter;
73                counter[0] = 1;
74                int cur = 0;
75                for(int row = 0; row < m; row++){
76                    cur += matrix[row][col_high] - ((col_low > 0) ? matrix[row][col_low-1] : 0);
77                    ans += counter[cur - target];
78                    // cout << row << ", [" << col_low << ", " << col_high << " ]" << ", cur: " << cur << ", ans: " << ans << endl;
79                    counter[cur]++;
80                }
81            }
82        }
83        
84        return ans;
85    }
86};
87
88//Treat submatrix as subarray and use sliding window
89//https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/303773/C%2B%2B-O(n3)-Simple-1D-Subarray-target-sum-applied-to-2D-array
90//Runtime: 5772 ms, faster than 59.72% of C++ online submissions for Number of Submatrices That Sum to Target.
91//Memory Usage: 455.5 MB, less than 100.00% of C++ online submissions for Number of Submatrices That Sum to Target.
92class Solution {
93public:
94    int subarraySum(vector<int>& arr, int target){
95        int res = 0, sum = 0;
96        map<int, int> counter;
97        counter[0] = 1;
98        for(int i = 0; i < arr.size(); i++){
99            sum += arr[i];
100            if(counter.find(sum - target) != counter.end()){
101                res += counter[sum - target];
102            }
103            counter[sum]++;
104        }
105        return res;
106    };
107    
108    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
109        int m = matrix.size(), n = matrix[0].size();
110        int ans = 0;
111        vector<int> row(n);
112        
113        for(int row_low = 0; row_low < m; row_low++){
114            //cumulative sum start from row_low
115            fill(row.begin(), row.end(), 0);
116            for(int row_high = row_low; row_high < m; row_high++){
117                //cumulative sum until row_high
118                for(int col = 0; col < n; col++){
119                    row[col] += matrix[row_high][col];
120                }
121                //think the submatrix as an array
122                //and then find its subarray's sum
123                ans += subarraySum(row, target);
124            }
125        }
126        
127        return ans;
128    }
129};

Cost

Complexity

Time
O(N^3), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.