Count Submatrices with Top-Left Element and Sum Less Than k - Problem

You're given a 2D integer matrix and need to find how many submatrices meet two specific criteria:

  1. The submatrix must contain the top-left element of the original matrix (position [0,0])
  2. The sum of all elements in the submatrix must be ≤ k

A submatrix is defined by its top-left corner at [0,0] and bottom-right corner at [i,j], containing all elements from [0,0] to [i,j] inclusive.

Example: If the matrix is [[1,2],[3,4]] and k=4, the valid submatrices are:

  • [1] (sum = 1 ≤ 4) ✓
  • [1,2] (sum = 3 ≤ 4) ✓
  • [[1],[3]] (sum = 4 ≤ 4) ✓
  • [[1,2],[3,4]] (sum = 10 > 4) ✗

Return the count of valid submatrices.

Input & Output

example_1.py — Basic Case
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]], k = 4
Output: 4
💡 Note: Valid submatrices: [1](1≤4), [1,1](2≤4), [[1],[1]](2≤4), [[1,1],[1,1]](4≤4). The 3×3 matrix has sum 9>4, so invalid.
example_2.py — Mixed Values
$ Input: grid = [[1,2,3],[4,5,6]], k = 10
Output: 3
💡 Note: Valid submatrices: [1](1≤10), [1,2](3≤10), [[1],[4]](5≤10). [[1,2,3]] has sum 6≤10 but [[1,2],[4,5]] has sum 12>10.
example_3.py — Edge Case
$ Input: grid = [[5]], k = 3
Output: 0
💡 Note: The only submatrix is [5], but 5 > 3, so no valid submatrices exist.

Constraints

  • 1 ≤ m, n ≤ 1000 (where m = grid.length, n = grid[0].length)
  • 1 ≤ grid[i][j] ≤ 1000
  • 1 ≤ k ≤ 109
  • All submatrices must include the top-left element grid[0][0]

Visualization

Tap to expand
Budget Spreadsheet$2$5$12$6$15$28k = $10Valid Budget RegionsCount = 3Prefix Sum Magic:• Build cumulative totals• Check each region instantly• Count valid budgetsTime: O(m×n)Space: O(1)
Understanding the Visualization
1
Start tracking expenses
Begin with the first expense at position [0,0]
2
Build running totals
Each cell shows total expenses from top-left to that position
3
Count valid budgets
Count how many rectangular regions stay within budget k
Key Takeaway
🎯 Key Insight: Prefix sums transform expensive O(m²n²) submatrix sum calculations into O(1) lookups, making the solution optimal at O(m×n) time complexity.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 5
23.5K Views
Medium Frequency
~15 min Avg. Time
892 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