#1504

Count Submatrices With All Ones

Medium
ArrayDynamic ProgrammingStackMatrixMonotonic StackDynamic ProgrammingMonotonic Stack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n²)
Space
O(1)
O(n)
💡

Intuition

Time O(m * n²)Space O(n)

The optimal solution leverages dynamic programming to count the number of submatrices with all ones by calculating the height of consecutive ones for each column and using that to find rectangles efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a height array to store the number of consecutive 1s for each column.
  2. 2Step 2: For each row, update the height array based on the current row's values.
  3. 3Step 3: For each column in the current row, calculate the number of rectangles that can be formed using the height array.
solution.py17 lines
1def countSubmatrices(mat):
2    if not mat:
3        return 0
4    m, n = len(mat), len(mat[0])
5    height = [0] * n
6    count = 0
7    for r in range(m):
8        for c in range(n):
9            height[c] = height[c] + 1 if mat[r][c] == 1 else 0
10        for c in range(n):
11            minHeight = height[c]
12            for k in range(c, n):
13                if height[k] == 0:
14                    break
15                minHeight = min(minHeight, height[k])
16                count += minHeight
17    return count

Complexity note: The time complexity is O(m * n²) because we iterate through each row and for each column in that row, we check the heights of columns to count rectangles, which can take linear time for each column.

  • 1Understanding how to represent the problem in terms of heights of consecutive ones is crucial.
  • 2Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.