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
Count Submatrices with Target SumInput Matrix0101Target = 1All Possible Submatrices1Single cells0,11×2 rows112×1 colsFull2×2 (sum=2)Count ResultsCount = 4submatriceswith sum = 1Found: 2 single cells + 1 column + 1 row = 4 submatricesAnswer: 4
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
Asked in
Google 8 Amazon 5 Facebook 4
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen