Dynamic Programming21 sections · 916 units
Open in Course

Challenge: 2D Submatrix Count

Counting with target sum

Count submatrices summing to target kk. This extends 1D subarray sum counting to 2D. Fix top and bottom rows. Compress columns into 1D array (column sums). Now apply 1D hashmap technique. For each pair of rows (r1,r2)(r1, r2), the column sums form a 1D array. Count subarrays summing to kk using the hashmap method. Time: O(n2m)O(n^2 \cdot m)

Time complexity: O(n2m)O(n^2 \cdot m) for an n×mn \times m matrix. There are O(n2)O(n^2) row pairs, and each 1D pass takes O(m)O(m).

Space complexity: O(nm)O(n \cdot m) for the prefix sum array.