Number of Submatrices That Sum to Target Problem
Description
LeetCode Problem 1074.
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'.
Example 1:

Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0
Output: 4
Explanation: The four 1x1 submatrices that only contain 0.
Example 2:
Input: matrix = [[1,-1],[-1,1]], target = 0
Output: 5
Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.
Example 3:
Input: matrix = [[904]], target = 0
Output: 0
Constraints:
1 <= matrix.length <= 1001 <= matrix[0].length <= 100-1000 <= matrix[i][j] <= 1000-10^8 <= target <= 10^8
Solution
Approach: Fix Two Rows, then Prefix Sums on Columns
First solve the one-dimensional version: count the subarrays of nums that sum to target. Walk through the array keeping the running sum s. A subarray ending here sums to target exactly when an earlier prefix had the sum s - target, so a hash map from prefix sum to how many times we have seen it answers this in one pass. Start the map with {0: 1} for the empty prefix, so subarrays that start at index 0 are counted too.
Now fix the top row top and the bottom row bottom of the submatrix. Every submatrix with these two rows is a range of columns, and its sum is the sum of the column totals in that range. Let col[k] be the sum of column k from row top to row bottom: the problem becomes the one-dimensional count on col.
For a fixed top, extend bottom one row at a time and add that row into col, so each pair of rows costs O(n) to update and O(n) to count.
Complexity: O(m2 · n) time for an m x n matrix: O(m2) row pairs and O(n) work for each. O(n) extra space for col and the hash map. (If m is much larger than n, fix two columns instead.)
class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
m, n = len(matrix), len(matrix[0])
ans = 0
for top in range(m):
col = [0] * n # col[k] = sum of column k from row top to row bottom
for bottom in range(top, m):
for k in range(n):
col[k] += matrix[bottom][k]
# Count subarrays of col that sum to target with prefix sums.
seen = {0: 1}
s = 0
for x in col:
s += x
ans += seen.get(s - target, 0)
seen[s] = seen.get(s, 0) + 1
return ans