#1074
Number of Submatrices That Sum to Target
HardArrayHash TableMatrixPrefix SumHash MapPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n^4) | O(n^2 * m) |
| Space | O(1) | O(m) |
💡
Intuition
Time O(n^2 * m)Space O(m)
The optimal approach uses a combination of prefix sums and a hash map to efficiently count the number of submatrices that sum to the target. This reduces the time complexity significantly by avoiding the need to calculate sums repeatedly.
⚙️
Algorithm
3 steps- 1Step 1: Precompute the prefix sums for the matrix to allow O(1) sum queries for any submatrix.
- 2Step 2: For each pair of row indices (r1, r2), calculate the cumulative sums for each column between these rows.
- 3Step 3: Use a hash map to count how many times each cumulative sum has occurred, allowing us to quickly find how many submatrices sum to the target.
solution.py19 lines
1# Full working Python code
2
3def numSubmatrixSumTarget(matrix, target):
4 if not matrix: return 0
5 count = 0
6 rows, cols = len(matrix), len(matrix[0])
7 for r1 in range(rows):
8 cum_sum = [0] * cols
9 for r2 in range(r1, rows):
10 for c in range(cols):
11 cum_sum[c] += matrix[r2][c]
12 sum_count = {0: 1}
13 current_sum = 0
14 for s in cum_sum:
15 current_sum += s
16 if current_sum - target in sum_count:
17 count += sum_count[current_sum - target]
18 sum_count[current_sum] = sum_count.get(current_sum, 0) + 1
19 return countℹ
Complexity note: The complexity is reduced because we only compute the sum of submatrices using cumulative sums and hash maps, which allows us to find the number of valid submatrices in linear time for each row pair.
- 1Using prefix sums allows for quick sum calculations of submatrices.
- 2Hash maps can efficiently track cumulative sums and their frequencies.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.