Count Submatrices With All Ones — LeetCode 1504 Python Solution

MediumStackArrayDynamic ProgrammingMatrixMonotonic Stack
Problem
#1504
Pattern
Stack
Reading time
3 min

The problem

Given an m x n binary matrix mat, return the number of submatrices that have all ones.

Example

Input
mat = [[1,0,1],[1,1,0],[1,1,0]]
Output
13
Explanation
There are 6 rectangles of side 1x1.

Python solution

Python
class Solution:
    def numSubmat(self, mat: List[List[int]]) -> int:
        m, n = len(mat), len(mat[0])
        g = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if mat[i][j]:
                    g[i][j] = 1 if j == 0 else 1 + g[i][j - 1]
        ans = 0
        for i in range(m):
            for j in range(n):
                col = inf
                for k in range(i, -1, -1):
                    col = min(col, g[k][j])
                    ans += col
        return ans

Complexity

MeasureComplexity
TimeO(m^2 \times n)
SpaceO(m \times n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1504. Count Submatrices With All Ones is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1504. Count Submatrices With All Ones?
LeetCode 1504. Count Submatrices With All Ones is rated Medium on LeetCode.
What is the time complexity of LeetCode 1504. Count Submatrices With All Ones?
The Python solution on this page runs in O(m^2 \times n).
What is the space complexity of LeetCode 1504. Count Submatrices With All Ones?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1504. Count Submatrices With All Ones cover?
LeetCode 1504. Count Submatrices With All Ones is tagged Stack, Array, Dynamic Programming, Matrix and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview