Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1504: Count Submatrices With All Ones

In this guide, we solve Leetcode #1504 Count Submatrices With All Ones in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Stack, Array, Dynamic Programming, Matrix, Monotonic Stack

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

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.

Python Solution

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

The time complexity is O(m2×n)O(m^2 \times n)O(m2×n), and the space complexity is O(m×n)O(m \times n)O(m×n). The space complexity is O(m×n)O(m \times n)O(m×n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy