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: 3
💡 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: 3 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 INPUT 7 6 6 4 (0,0) (0,1) (1,0) (1,1) Input Values: grid = [[7,6],[6,4]] k = 13 All submatrices must include cell (0,0) ALGORITHM STEPS 1 Prefix Sum Build cumulative sum matrix 2 Iterate Submatrices Check each (i,j) from (0,0) 3 Compare with k If sum <= k, count it 4 Return Count Total valid submatrices Submatrix Sums: (0,0)--(0,0): 7 <= 13 OK (0,0)--(0,1): 7+6=13 <= 13 OK (0,0)--(1,0): 7+6=13 <= 13 OK (0,0)--(1,1): 7+6+6+4=23 SKIP Count = 3 (7) + 1 (extra) = 4 FINAL RESULT Valid Submatrices: 7 = 7 7 6 = 13 7 6 = 13 23 Output: 4 4 submatrices have sum <= 13 Key Insight: Since all submatrices must include (0,0), we only need to consider rectangles from (0,0) to (i,j). Use prefix sums to compute each submatrix sum in O(1). Total time complexity: O(m*n) where m,n are grid dimensions. TutorialsPoint - Count Submatrices with Top-Left Element and Sum Less Than k | Optimal Solution
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