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
Count Submatrices with Top-Left Element and Sum ≤ kInput Grid:7664k = 13Valid Submatrices:7sum=7≤13 ✓76sum=13≤1376sum=13≤13 ✓7 66 4sum=23>13 ✗Output: 4 valid submatricesCount all rectangles starting from (0,0) with sum ≤ k
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
Asked in
Google 25 Amazon 20 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
890 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