Number of Submatrices That Sum to Target - Problem
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'.
Input & Output
Example 1 — Basic 2x2 Matrix
$
Input:
matrix = [[0,1],[0,1]], target = 1
›
Output:
4
💡 Note:
Four submatrices sum to 1: [0,1] (top-right cell), [0,1] (bottom-right cell), [[1],[1]] (right column), and [1] (each individual 1)
Example 2 — Larger Matrix
$
Input:
matrix = [[1,-1],[-1,1]], target = 0
›
Output:
5
💡 Note:
Five submatrices sum to 0: four 2x1 rectangles ([1,-1], [-1,1], [1],[-1]], [[1],[-1]]) and the entire 2x2 matrix
Example 3 — Single Element
$
Input:
matrix = [[904]], target = 0
›
Output:
0
💡 Note:
Only one submatrix exists (the single cell with value 904), but it doesn't sum to 0
Constraints
- 1 ≤ matrix.length ≤ 100
- 1 ≤ matrix[i].length ≤ 100
- -1000 ≤ matrix[i][j] ≤ 1000
- -108 ≤ target ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
2D matrix with target sum to find
2
Find Submatrices
Enumerate all possible rectangles
3
Count Matches
Count how many sum to target
Key Takeaway
🎯 Key Insight: Convert 2D matrix problem to multiple 1D array problems using prefix sums
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code