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.length n == grid[i].length1 <= n, m <= 1000 0 <= grid[i][j] <= 10001 <= k <= 109This approach leverages the cumulative prefix sum technique to quickly calculate the sum of submatrices starting from the top-left to any (i, j). The idea is to iterate through all possible submatrices starting at the top-left, using a prefix sum matrix to obtain the total sum efficiently. If the sum is less than or equal to k, we count it.
Initially, we calculate the prefix sum matrix prefix using a nested loop to preprocess submatrix sums efficiently. Here, prefix[i][j] holds the sum of elements from top-left (0,0) to the current cell (i, j). Further we iterate through each cell, (r, c), forming submatrices starting from (0,0) until that cell and if their sum is less than or equal to k, we increment the counter.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n)
Space Complexity: O(m * n)
Instead of a full 2D prefix sum array, this approach uses a 1D prefix sum and iterative row expansion to calculate submatrix sums and maintain under k leveraging a sliding window or two-pointer technique.
This implementation calculates prefix sums on the fly as rows are included in the submatrices incrementally and checks if the sum remains within the desired limit k. The reset prefixRow array aids in accumulating these values efficiently.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n * n)
Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Approach 1: Brute Force with Cumulative Prefix Sum | Time Complexity: O(m * n) |
| Approach 2: Optimized Summation with 1D Prefix Array | Time Complexity: O(m * n * n) |
Number of Submatrices that Sum to Target - Leetcode 1074 - Python • NeetCodeIO • 17,266 views views
Watch 9 more video solutions →Practice Count Submatrices with Top-Left Element and Sum Less Than k with our built-in code editor and test cases.
Practice on FleetCode