Find Sorted Submatrices With Maximum Element at Most K Problem
Description
LeetCode Problem 3359.
You are given a 2D matrix grid of size m x n. You are also given a non-negative integer k.
Return the number of submatrices of grid that satisfy the following conditions:
- The maximum element in the submatrix less than or equal to
k. - Each row in the submatrix is sorted in non-increasing order.
A submatrix (x1, y1, x2, y2) is a matrix that forms by choosing all cells grid[x][y] where x1 <= x <= x2 and y1 <= y <= y2.
Example 1:
Input: grid = [[4,3,2,1],[8,7,6,1]], k = 3
Output: 8
Explanation:

The 8 submatrices are:
- [[1]]
- [[1]]
- [[2,1]]
- [[3,2,1]]
- [[1],[1]]
- [[2]]
- [[3]]
- [[3,2]]
Example 2:
Input: grid = [[1,1,1],[1,1,1],[1,1,1]], k = 1
Output: 36
Explanation:
There are 36 submatrices of grid. All submatrices have their maximum element equal to 1.
Example 3:
Input: grid = [[1]], k = 1
Output: 1
Constraints:
1 <= m == grid.length <= 10^31 <= n == grid[i].length <= 10^31 <= grid[i][j] <= 10^91 <= k <= 10^9
Solution
Approach: Run Lengths + Monotonic Stack
A submatrix counts when its largest element is at most k and every row is non-increasing from left to right. For each cell, store run[i][j]: how many cells, ending at (i, j), form a non-increasing row run in which every cell is at most k (0 if the cell itself exceeds k).
Fix the right column j. A submatrix with right column j, rows a..b and width w is valid exactly when w is at most the minimum of run[a..b][j]. So the number of valid submatrices for that column is the sum, over all row ranges, of the minimum of run in the range. A monotonic stack computes this in linear time: f[i] is the sum of range minimums over ranges ending at row i, built from the previous smaller element p as run[i][j] * (i - p) + f[p]. Summing all f[i] gives the answer.
Complexity: O(m * n) time and O(m * n) space for an m by n grid.
class Solution:
def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
# run[i][j]: length of the non-increasing run of cells <= k ending at (i, j)
run = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if grid[i][j] > k:
continue
if j > 0 and run[i][j - 1] > 0 and grid[i][j - 1] >= grid[i][j]:
run[i][j] = run[i][j - 1] + 1
else:
run[i][j] = 1
ans = 0
for j in range(n):
# sum of the minimum over all row ranges, with a monotonic stack
stack = []
f = [0] * m # f[i]: sum of minimums of ranges ending at row i
for i in range(m):
v = run[i][j]
while stack and run[stack[-1]][j] >= v:
stack.pop()
p = stack[-1] if stack else -1
f[i] = v * (i - p) + (f[p] if p >= 0 else 0)
ans += f[i]
stack.append(i)
return ans