923. Find Sorted Submatrices With Maximum Element at Most K

You are provided with a two-dimensional matrix grid of size m x n and an integer k.

Your task is to determine the number of submatrices of grid that satisfy both of the following conditions:

  • Bounded Maximum: The highest element within the submatrix is less than or equal to k.
  • Row-wise Non-Increasing Order: In the submatrix, every row must be sorted in non-increasing order (i.e., each element is greater than or equal to the element immediately to its right).

A submatrix is defined by the coordinates (x1, y1, x2, y2) and consists of all elements grid[x][y] such that x1 ≤ x ≤ x2 and y1 ≤ y ≤ y2.

Return the total count of submatrices meeting the above criteria.

Example 1:

Input : grid = [[4,3], [2,1]], k = 3

Output : 5

Explanation :

The submatrices of grid that have a maximum element at most 3 and whose rows are in non-increasing order are:

  • Submatrix consisting of the single element 3 at position (0,1): [[3]]
  • Submatrix consisting of the single element 2 at position (1,0): [[2]]
  • Submatrix consisting of the single element 1 at position (1,1): [[1]]
  • Submatrix from row 1 covering columns 0 to 1: [[2,1]]
  • Submatrix from column 1 covering rows 0 to 1: [[3], [1]]

Example 2:

Input : grid = [[2,2,2], [2,2,2], [2,2,2]], k = 2

Output : 36

Explanation :

Every possible submatrix of grid has all elements equal to 2, which is ≤ k. Also, since all rows are identical, every row in any submatrix is trivially in non-increasing order. In a 3 x 3 matrix, the total number of submatrices is given by ((3 × 4) / 2) × ((3 × 4) / 2) = 6 × 6 = 36.

Now Your Turn!

Pick the correct output for the given input

Input : grid = [[5]], k = 5

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ m = grid.length ≤ 10³
  • 1 ≤ n = grid[i].length ≤ 10³
  • 1 ≤ grid[i][j] ≤ 10⁹
  • 1 ≤ k ≤ 10⁹

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long countSubmatrices(vector<vector<int>> &grid, int k) {
// Your code goes here
}
};
Test Case

Input:

Grid
K