Count Submatrices with Top-Left Element and Sum Less Than k Problem
#3070
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3070.
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.
Example 1:

Input: grid = [[7,6,3],[6,6,1]], k = 18
Output: 4
Explanation: There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.
Example 2:

Input: grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20
Output: 6
Explanation: There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.
Constraints:
m == grid.lengthn == grid[i].length1 <= n, m <= 10000 <= grid[i][j] <= 10001 <= k <= 10^9
Solution
Approach: Two-Dimensional Prefix Sum
A submatrix containing the top-left cell is determined by its bottom-right corner, so we count the corners (i, j) whose prefix sum s[i][j] is at most k. The prefix sums follow s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + grid[i-1][j-1].
Complexity: O(mn) time and O(mn) extra space, where m and n are the numbers of rows and columns.
class Solution:
def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
s = [[0] * (len(grid[0]) + 1) for _ in range(len(grid) + 1)]
ans = 0
for i, row in enumerate(grid, 1):
for j, x in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
ans += s[i][j] <= k
return ans