Number of Submatrices That Sum to Target - Problem

Given a 2D matrix and a target sum, count how many submatrices have elements that sum exactly to the target value.

A submatrix is defined by coordinates (x1, y1, x2, y2) representing all cells matrix[x][y] where x1 ≤ x ≤ x2 and y1 ≤ y ≤ y2. Two submatrices are considered different if they have any coordinate that differs.

Example: In matrix [[0,1,0],[1,1,1],[0,1,0]] with target 0, submatrices like [0] (single cell) and [[1,0],[1,0]] (2x2 region) both sum to target values and should be counted.

This is a challenging problem that combines prefix sums with hash table techniques to efficiently count valid rectangular regions in a 2D space.

Input & Output

example_1.py — Basic Matrix
$ Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
💡 Note: Four submatrices sum to 0: single cells [0] at positions (0,0), (0,2), (2,0), (2,2). Each forms a 1×1 submatrix with sum 0.
example_2.py — Larger Target
$ Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
💡 Note: Five submatrices sum to 0: four 1×1 submatrices don't work since all values are ±1, but we have: [1,-1], [-1,1] (1×2 rectangles), [1;-1], [-1;1] (2×1 rectangles), and the full 2×2 matrix.
example_3.py — Single Element
$ Input: matrix = [[904]], target = 0
Output: 0
💡 Note: The only submatrix is the single cell [904], which sums to 904, not 0. Therefore, no submatrix sums to target.

Visualization

Tap to expand
Original Matrix10-1110011Compressed2, 1, -1Hash Tableprefix=0: count=1prefix=2: count=1prefix=3: count=1prefix=2: count=2Found: 3-3=0 ✓
Understanding the Visualization
1
Select Row Range
Pick top and bottom boundaries (like selecting row span in Excel)
2
Compress to 1D
Sum each column between the selected rows to create a single array
3
Find Target Subarrays
Use hash table technique to find all subarrays in this 1D array that sum to target
4
Repeat for All Pairs
Try every possible row pair combination and sum up all results
Key Takeaway
🎯 Key Insight: Transform the 2D problem into multiple 1D problems using row compression, then apply the proven hash table technique for subarray sums

Time & Space Complexity

Time Complexity
⏱️
O(m² × n)

O(m²) to try all row pairs, O(n) to process each compressed array with hash table

n
2n
Linear Growth
Space Complexity
O(n)

Hash table stores at most n prefix sums, plus O(n) for compressed array

n
2n
Linearithmic Space

Constraints

  • 1 ≤ matrix.length ≤ 100
  • 1 ≤ matrix[0].length ≤ 100
  • -1000 ≤ matrix[i][j] ≤ 1000
  • -108 ≤ target ≤ 108
  • All matrix elements and target fit in 32-bit integers
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 23
52.3K Views
Medium-High Frequency
~25 min Avg. Time
1.8K 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