↓Skip to main content
  1. LeetCode/

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

·2 mins· ·
LeetCode Medium Array Matrix Prefix-Sum
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2024-03-03

  • Submissions: Wrong Answer ×2 → Accepted

Approach
#

A submatrix containing (0, 0) is determined by its bottom-right corner (i, j), and its sum is the 2D prefix sum P[i][j] = grid[i][j] + P[i - 1][j] + P[i][j - 1] - P[i - 1][j - 1] (Prefix Sum). Subtract the doubly counted P[i - 1][j - 1]. Count how many P[i][j] <= k.

My Attempts
#

It failed twice during the 2024 contest:

  • Attempt 1 accumulated top and left in place without subtracting the upper-left, counting the overlap twice: for [[1, 0], [4, 4]], k = 9 the bottom-right became 10, returning 3 instead of 4.
  • Then row prefix sums plus the previous row’s results (no double counting), but with < k: [[3]], k = 3 returned 0. <= passed.

Solution
#

class Solution:
    def countSubmatrices(self, grid: List[List[int]], k: int) -> int:
        m, n = len(grid), len(grid[0])
        P = [[0] * (n + 1) for _ in range(m + 1)]
        count = 0
        for i in range(m):
            for j in range(n):
                P[i + 1][j + 1] = grid[i][j] + P[i][j + 1] + P[i + 1][j] - P[i][j]
                count += P[i + 1][j + 1] <= k
        return count

Complexity
#

Time O(mn), space O(mn).

Mistakes to Avoid
#

  • Subtract the upper-left term, or the overlap counts twice.
  • The condition is <= k.

Interview Explanation
#

Submatrices containing the top-left corner correspond to the 2D prefix sums ending at each cell; I compute them as top plus left minus top-left and count those at most k. Time O(mn).

Related

LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·2 mins
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 note: count each value on and off the Y, enumerate the Y value a and background value b (a != b), and take the fewest cells to change
LeetCode 240: Search a 2D Matrix II
·2 mins
LeetCode Medium Array Binary-Search Divide-and-Conquer Matrix
LeetCode 240 note: start at the top-right corner, moving left when larger and down when smaller, eliminating a row or column each step
LeetCode 48: Rotate Image
·2 mins
LeetCode Medium Array Math Matrix
LeetCode 48 note: rotating 90 degrees clockwise is a transpose followed by reversing each row, both in place
LeetCode 417: Pacific Atlantic Water Flow
·3 mins
LeetCode Medium Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 417 note: walk inward from each ocean’s shore to cells no lower than the current one; cells reached from both oceans are the answer
LeetCode 238: Product of Array Except Self
·2 mins
LeetCode Medium Array Prefix-Sum
LeetCode 238 note: each answer is the product of everything to the left times everything to the right; two passes, no division
LeetCode 73: Set Matrix Zeroes
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 73 note: record which rows and columns contain a 0 first, then update afterward; the follow-up uses the first row and column as markers