Count Submatrices with Top-Left Element and Sum Less Than k - Problem
You are given a 0-indexed integer matrix grid and an integer k.
Return the number of submatrices that contain the top-left element of the grid, and have a sum less than or equal to k.
A submatrix is a rectangular region within the matrix. For this problem, we only consider submatrices that include the element at position (0,0).
Input & Output
Example 1 — Basic Case
$
Input:
grid = [[7,6],[6,4]], k = 13
›
Output:
4
💡 Note:
All possible submatrices: (0,0)→sum=7≤13 ✓, (0,0)→(0,1)→sum=13≤13 ✓, (0,0)→(1,0)→sum=13≤13 ✓, (0,0)→(1,1)→sum=23>13 ✗. Total: 4 valid submatrices.
Example 2 — Single Element
$
Input:
grid = [[7]], k = 6
›
Output:
0
💡 Note:
Only one submatrix: (0,0) with sum=7 > 6, so no valid submatrices.
Example 3 — All Valid
$
Input:
grid = [[1,1],[1,1]], k = 10
›
Output:
4
💡 Note:
All submatrices have small sums: 1, 2, 2, 4 - all ≤ 10, so count = 4.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 100
- 0 ≤ grid[i][j] ≤ 1000
- 0 ≤ k ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
2D grid and threshold k
2
Process
Check all rectangles from (0,0) to (i,j)
3
Output
Count of valid submatrices
Key Takeaway
🎯 Key Insight: 2D prefix sums transform O(mn) rectangle sum queries into O(1) lookups
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code