Back to March Back to Year 2026
MEDIUM 18 Mar 2026 View on LeetCode

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

</> Solution

/**
 * Problem: LeetCode 3070 - Count Submatrices with Top-Left Element and Sum Less Than k
 * Difficulty: Medium
 * Language: Java
 * Author: CodeByTushu
 */
class Solution {
    public int countSubmatrices(int[][] grid, int k) {
        int m = grid.length;
        int n = grid[0].length;
        int count = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i > 0) {
                    grid[i][j] += grid[i - 1][j];
                }
                if (j > 0) {
                    grid[i][j] += grid[i][j - 1];
                }
                if (i > 0 && j > 0) {
                    grid[i][j] -= grid[i - 1][j - 1];
                }

                if (grid[i][j] <= k) {
                    count++;
                }
            }
        }

        return count;
    }
}

TIME COMPLEXITY

O(m * n)

SPACE COMPLEXITY

O(1)

TOPICS

Array Matrix Prefix Sum