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
Number of Submatrices That Sum to Target INPUT matrix (2x2): 0 1 0 1 col 0 col 1 r0 r1 target = 1 Find submatrices with sum = 1 ALGORITHM (Hash) 1 Prefix Sum Columns Compute cumulative sum for each column 2 Fix Row Bounds For each pair (r1, r2) compress to 1D array 3 HashMap Counting Track prefix sums count sum-target pairs 4 Accumulate Result Sum all valid submatrix counts HashMap sum count 0 1 1 2 2 1 FINAL RESULT 4 Valid Submatrices Found: #1: cell(0,1) 0 1 0 1 #2: cell(1,1) 0 1 0 1 #3: col1(0:1) 0 1 0 1 sum=2? No! #4: row0 0 1 0 1 Output: 4 OK - 4 submatrices sum to target 1 Key Insight: Reduce 2D submatrix sum problem to 1D subarray sum using prefix sums on columns. For each row pair (r1,r2), use HashMap to count subarrays with sum=target in O(cols) time. Total complexity: O(rows^2 * cols) with O(cols) space for the hash map. TutorialsPoint - Number of Submatrices That Sum to Target | Hash Approach
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