Number of Submatrices That Sum to Target (LeetCode 1074): Solution and Explanation
Given an integer matrix and a target, count every rectangle of cells (any size, any position) whose elements add up to the target.
Intuition
There are O(m^2 * n^2) rectangles, and even with 2D prefix sums checking each one costs O(1), so brute force is O(m^2 * n^2). For a 100 x 100 matrix that is 10^8 checks, too slow.
Fix the left and right columns of the rectangle, c1 and c2. Now every rectangle inside that band is just a run of consecutive rows. If you squash each row of the band into its sum, you get a plain 1D array of length m.
Counting runs of a 1D array that sum to target is a well known problem: keep a running total cur and a hash map of how often each earlier running total appeared. A run ending here sums to target exactly when some earlier total equals cur - target.
So the 2D problem becomes O(n^2) copies of the 1D problem, each O(m). Row prefix sums make each row's band sum a single subtraction.
Approach: Column band plus prefix-sum hash map
- Build row prefix sums
pre[r][c + 1] = pre[r][c] + matrix[r][c]. - For every pair
c1 <= c2, start a mapseen = {0: 1}andcur = 0. - For each row
r, add the band sumpre[r][c2 + 1] - pre[r][c1]tocur. - Add
seen[cur - target](0 if missing) tocount: each such earlier total marks the row just above a valid rectangle's top edge. - Record
curinseen, move to the next row, and returncountafter all bands.
Step-by-step example
matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
- Band c1 = 0, c2 = 0 gives band sums [0, 1, 0]. Row 0: cur = 0, seen has 0 once, so 1 rectangle (cell (0,0)). Store 0.
- Row 1: cur = 1, nothing to match. Row 2: cur = 1, and 1 is in seen once, so cell (2,0) counts. count = 2.
- Bands (0,1), (0,2), (1,1) and (1,2) have running totals that never repeat, so they add nothing.
- Band c1 = 2, c2 = 2 has band sums [0, 1, 0] again and adds cells (0,2) and (2,2). count = 4.
- All 6 bands are done, so the answer is 4.
Code: Python, Java, C++
1class Solution:
2 def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
3 m, n = len(matrix), len(matrix[0])
4 pre = [[0] * (n + 1) for _ in range(m)]
5 for r in range(m):
6 for c in range(n):
7 pre[r][c + 1] = pre[r][c] + matrix[r][c]
8 count = 0
9 for c1 in range(n):
10 for c2 in range(c1, n):
11 seen = {0: 1}
12 cur = 0
13 for r in range(m):
14 cur += pre[r][c2 + 1] - pre[r][c1]
15 count += seen.get(cur - target, 0)
16 seen[cur] = seen.get(cur, 0) + 1
17 return count1class Solution {
2 public int numSubmatrixSumTarget(int[][] matrix, int target) {
3 int m = matrix.length, n = matrix[0].length;
4 int[][] pre = new int[m][n + 1];
5 for (int r = 0; r < m; r++) {
6 for (int c = 0; c < n; c++) {
7 pre[r][c + 1] = pre[r][c] + matrix[r][c];
8 }
9 }
10 int count = 0;
11 for (int c1 = 0; c1 < n; c1++) {
12 for (int c2 = c1; c2 < n; c2++) {
13 Map<Integer, Integer> seen = new HashMap<>();
14 seen.put(0, 1);
15 int cur = 0;
16 for (int r = 0; r < m; r++) {
17 cur += pre[r][c2 + 1] - pre[r][c1];
18 count += seen.getOrDefault(cur - target, 0);
19 seen.merge(cur, 1, Integer::sum);
20 }
21 }
22 }
23 return count;
24 }
25}1class Solution {
2public:
3 int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {
4 int m = matrix.size(), n = matrix[0].size();
5 vector<vector<int>> pre(m, vector<int>(n + 1, 0));
6 for (int r = 0; r < m; r++) {
7 for (int c = 0; c < n; c++) {
8 pre[r][c + 1] = pre[r][c] + matrix[r][c];
9 }
10 }
11 int count = 0;
12 for (int c1 = 0; c1 < n; c1++) {
13 for (int c2 = c1; c2 < n; c2++) {
14 unordered_map<int, int> seen;
15 seen[0] = 1;
16 int cur = 0;
17 for (int r = 0; r < m; r++) {
18 cur += pre[r][c2 + 1] - pre[r][c1];
19 auto it = seen.find(cur - target);
20 if (it != seen.end()) count += it->second;
21 seen[cur]++;
22 }
23 }
24 }
25 return count;
26 }
27};Time and space complexity
O(m * n^2)
There are n(n + 1)/2 column bands and each one does a single O(m) pass with O(1) hash map operations per row. Transposing first when m < n gives O(min(m, n)^2 * max(m, n)).
O(m * n)
The row prefix sums take m * (n + 1) integers, and the map for one band holds at most m + 1 entries.
Other approaches
2D prefix sums and every rectangle (time O(m^2 * n^2), space O(m * n))
Build a 2D prefix table so any rectangle sum is four lookups, then enumerate all pairs of rows and all pairs of columns. Simple and correct, but O(m^2 * n^2) is too slow at the upper limits.
Fix a row band instead (time O(m^2 * n), space O(m * n))
Symmetric version: fix top and bottom rows, collapse each column, and run the 1D count across columns. Choose whichever dimension is smaller to fix pairs of.
Common mistakes
- Forgetting to seed the map with
{0: 1}, which misses every rectangle that starts at row 0. - Reusing the map across column bands. It must be reset for every (c1, c2) pair.
- Recording
curbefore looking upcur - target. With target = 0 that counts an empty rectangle. - Using a sliding window: values can be negative, so the window sum is not monotonic and two pointers do not work.
Frequently asked questions
Why does seen[cur - target] count rectangles?
If the running total after row i was cur - target and it is cur after row r, then rows i + 1 through r of the band add up to exactly target. Each earlier occurrence is a different top edge.
Why start the map with 0 mapped to 1?
It stands for the empty prefix above row 0, so a rectangle that begins at the top row is counted when cur itself equals target.
Can the count overflow a 32-bit integer?
No. A 100 x 100 matrix has (100 * 101 / 2)^2, about 25.5 million rectangles, which fits easily.
What is the time complexity of Number of Submatrices That Sum to Target?
O(m * n^2) with column bands, or O(min(m, n)^2 * max(m, n)) if you band along the shorter side.