Count Submatrices With All Ones Problem
Description
LeetCode Problem 1504.
Given an m x n binary matrix mat, return the number of submatrices that have all ones.
Example 1:

Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 13
Explanation:
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
Example 2:

Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]
Output: 24
Explanation:
There are 8 rectangles of side 1x1.
There are 5 rectangles of side 1x2.
There are 2 rectangles of side 1x3.
There are 4 rectangles of side 2x1.
There are 2 rectangles of side 2x2.
There are 2 rectangles of side 3x1.
There is 1 rectangle of side 3x2.
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.
Constraints:
1 <= m, n <= 150mat[i][j]is either0or1.
Solution
Approach: Row Widths and a Monotonic Stack per Column
First compute width[i][j]: how many 1's end at (i, j) going left in row i (0 if mat[i][j] is 0). Now count the all-ones submatrices by their bottom-right corner (i, j). If such a submatrix starts at row t, it can be as wide as the smallest width[r][j] for r in t..i, and each width from 1 up to that minimum is one submatrix. So the count for (i, j) is the sum, over every top row t <= i, of min(width[t..i][j]).
Summing these minimums by walking up from every cell costs O(m) per cell. A monotonic stack per column does it in amortized O(1):
- Go down column
jand keep a stack of rows whose widths strictly increase from bottom to top, together withcount[r], the number of submatrices with bottom-right corner(r, j). - At row
iwith widthw, pop every row whose width is>= w. Those rows are no narrower than rowi, so for any top row above them the minimum is decided by rowior by something higher. - If the stack is empty, every row
0..ihas width at leastw, socount[i] = w * (i + 1). - Otherwise let
rbe the row on top, the nearest row above with a smaller width. Tops in rowsr+1..iare limited byw, which givesw * (i - r). Tops at rowror above are limited exactly as they are for corner(r, j), since rowris narrower than every row between, which givescount[r]. Socount[i] = count[r] + w * (i - r).
Add count[i] to the answer and push row i.
Complexity: O(m·n) time, because every row is pushed and popped at most once per column, and O(m·n) space for the widths.
class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
# width[i][j]: length of the run of ones in row i that ends at column j
width = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if mat[i][j]:
width[i][j] = 1 + (width[i][j - 1] if j else 0)
ans = 0
for j in range(n):
# (width, row, count) with widths strictly increasing; count is the number of
# all-ones submatrices whose bottom-right corner is (row, j)
stack = []
for i in range(m):
w = width[i][j]
while stack and stack[-1][0] >= w:
stack.pop()
if stack:
_, r, c = stack[-1]
count = c + w * (i - r) # tops in rows r+1..i are limited by w
else:
count = w * (i + 1)
ans += count
stack.append((w, i, count))
return ans