#3070
Count Submatrices with Top-Left Element and Sum Less Than k
MediumArrayMatrixPrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach uses prefix sums and a data structure to efficiently count submatrices with sums less than k. By leveraging prefix sums, we can quickly calculate the sum of any submatrix.
⚙️
Algorithm
5 steps- 1Step 1: Compute a prefix sum matrix for the grid.
- 2Step 2: Iterate through all possible bottom-right corners of submatrices starting from (0,0).
- 3Step 3: For each bottom-right corner, calculate the sum using the prefix sum matrix.
- 4Step 4: Use a sorted data structure to count how many prefix sums are less than k.
- 5Step 5: Return the total count of valid submatrices.
solution.py21 lines
1# Full working Python code
2import bisect
3
4def countSubmatrices(grid, k):
5 m, n = len(grid), len(grid[0])
6 prefix_sum = [[0] * (n + 1) for _ in range(m + 1)]
7 for i in range(m):
8 for j in range(n):
9 prefix_sum[i + 1][j + 1] = grid[i][j] + prefix_sum[i][j + 1] + prefix_sum[i + 1][j] - prefix_sum[i][j]
10 count = 0
11 for i in range(m):
12 for j in range(n):
13 sums = []
14 for x in range(i + 1):
15 current_sum = prefix_sum[i + 1][j + 1] - prefix_sum[x][j + 1]
16 sums.append(current_sum)
17 sums.sort()
18 for s in sums:
19 if s < k:
20 count += 1
21 return countℹ
Complexity note: The time complexity is O(n log n) due to sorting the sums for each submatrix, while the space complexity is O(n) for storing prefix sums.
- 1Using prefix sums allows for efficient sum calculations of submatrices.
- 2Sorting helps quickly count how many sums are less than k.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.