Find Sorted Submatrices With Maximum Element at Most K - Problem

๐ŸŽฏ Find Sorted Submatrices With Maximum Element at Most K

Imagine you're a data analyst working with a 2D grid of numbers, and you need to identify specific rectangular regions that meet strict criteria. Your task is to count how many submatrices satisfy two important conditions:

  • ๐Ÿ”ข The maximum element in the submatrix is โ‰ค k
  • ๐Ÿ“‰ Each row in the submatrix is sorted in non-increasing order (descending)

A submatrix is any rectangular region you can select from the grid by choosing coordinates (x1, y1) as the top-left corner and (x2, y2) as the bottom-right corner, where all cells grid[x][y] with x1 โ‰ค x โ‰ค x2 and y1 โ‰ค y โ‰ค y2 are included.

Example: For grid [[7,6,3],[7,6,3]] with k=6, the submatrix from (0,1) to (1,2) containing [[6,3],[6,3]] is valid because:

  • Maximum element is 6 โ‰ค k
  • Both rows [6,3] and [6,3] are in non-increasing order

Return the total count of all such valid submatrices.

Input & Output

example_1.py โ€” Basic Case
$ Input: grid = [[7,6,3],[7,6,3]], k = 6
โ€บ Output: 4
๐Ÿ’ก Note: Valid submatrices: [[6]], [[3]], [[6,3]], and [[6,3],[6,3]]. All satisfy max โ‰ค k and non-increasing rows.
example_2.py โ€” Single Row
$ Input: grid = [[7,6,3]], k = 3
โ€บ Output: 2
๐Ÿ’ก Note: Only [[3]] and [[6,3]] are valid. [7] and [7,6] have elements > k.
example_3.py โ€” No Valid Submatrices
$ Input: grid = [[1,3,5],[2,4,6]], k = 2
โ€บ Output: 3
๐Ÿ’ก Note: Valid submatrices are [[1]], [[2]], and single cell submatrices with value โ‰ค 2. Rows are not properly sorted.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 โ‰ค m, n โ‰ค 1000
  • 0 โ‰ค grid[i][j] โ‰ค 1000
  • 0 โ‰ค k โ‰ค 1000

Visualization

Tap to expand
๐Ÿซ Chocolate Factory Quality ControlChocolate Tray (Sweetness Levels)763763โœ“ Valid SectionInspector Checklistโœ“ Max sweetness โ‰ค 6โœ“ Row 1: [6,3] decreasingโœ“ Row 2: [6,3] decreasingโœ“ Valid rectangular section!Status: APPROVEDโŒ Too Sweet (7 > k=6)โœ… Perfect Quality Control
Understanding the Visualization
1
Setup Inspection
Examine rectangular sections of chocolate trays
2
Check Sweetness
Ensure no chocolate exceeds sweetness limit k
3
Verify Arrangement
Confirm each row goes from sweetest to least sweet
4
Count Valid Sections
Tally all sections meeting both criteria
Key Takeaway
๐ŸŽฏ Key Insight: By treating each row as a base for building histograms and using monotonic stacks, we efficiently count all valid rectangular regions without redundant checking.
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 31
29.6K Views
Medium Frequency
~32 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen