Find Sorted Submatrices With Maximum Element at Most K - Problem
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 is less than or equal to k
- Each row in the submatrix is sorted in non-increasing order
A submatrix (x1, y1, x2, y2) is formed by choosing all cells grid[x][y] where x1 <= x <= x2 and y1 <= y <= y2.
Input & Output
Example 1 — Basic Case
$
Input:
grid = [[7,6,3],[2,1,0]], k = 2
›
Output:
4
💡 Note:
Valid submatrices: (0,2,0,2) contains [3], (1,0,1,2) contains [2,1,0], (1,1,1,1) contains [1], (1,1,1,2) contains [1,0]. All have max ≤ 2 and non-increasing rows.
Example 2 — Single Cell
$
Input:
grid = [[1,2,3],[4,5,6]], k = 2
›
Output:
2
💡 Note:
Only single cells with value ≤ 2 are valid: grid[0][0]=1 and grid[1][0]=1. Multi-cell submatrices fail row sorting or max constraint.
Example 3 — All Valid
$
Input:
grid = [[2,1],[1,0]], k = 5
›
Output:
6
💡 Note:
All elements ≤ 5 and all rows non-increasing. Valid submatrices: 4 single cells + 2 row submatrices + entire 2×2 matrix = 6 total.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- 0 ≤ grid[i][j] ≤ 100
- 0 ≤ k ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
2D grid with elements and threshold k
2
Check Constraints
Validate max ≤ k and rows non-increasing
3
Count Valid
Return number of qualifying submatrices
Key Takeaway
🎯 Key Insight: Use monotonic stack to efficiently count rectangles for each column range, avoiding redundant submatrix validation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code