Number of Submatrices That Sum to Target (LeetCode 1074): Solution and Explanation

Hard
Array
Hash Table
Matrix
Prefix Sum

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

  1. Build row prefix sums pre[r][c + 1] = pre[r][c] + matrix[r][c].
  2. For every pair c1 <= c2, start a map seen = {0: 1} and cur = 0.
  3. For each row r, add the band sum pre[r][c2 + 1] - pre[r][c1] to cur.
  4. Add seen[cur - target] (0 if missing) to count: each such earlier total marks the row just above a valid rectangle's top edge.
  5. Record cur in seen, move to the next row, and return count after all bands.

Step-by-step example

matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
  1. 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.
  2. Row 1: cur = 1, nothing to match. Row 2: cur = 1, and 1 is in seen once, so cell (2,0) counts. count = 2.
  3. Bands (0,1), (0,2), (1,1) and (1,2) have running totals that never repeat, so they add nothing.
  4. Band c1 = 2, c2 = 2 has band sums [0, 1, 0] again and adds cells (0,2) and (2,2). count = 4.
  5. 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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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

Space

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 cur before looking up cur - 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.