15% off all plans & roadmaps Use code
See plansCount Square Submatrices with All Ones
- LeetCode 1277
- Medium
- Dynamic Programming (DP) Patterns
- 2D Array (Unique Paths on Grid)
Updated
TL;DR: For every cell, compute the side of the largest all-ones square whose bottom-right corner is that cell. That one number also counts every smaller square ending there, so summing the table gives the answer in one O(m * n) pass.
Problem
Given an m * n binary matrix (only 0s and 1s), return the number of square submatrices whose cells are all 1s.
Example 1
Input: matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]] Output: 15 Explanation: There are 10 squares of side 1, 4 squares of side 2, and 1 square of side 3. The total is 10 + 4 + 1 = 15.
Example 2
Input: matrix = [[1,0,1],[1,1,0],[1,1,0]] Output: 7 Explanation: There are 6 squares of side 1 and 1 square of side 2. The total is 6 + 1 = 7.
Constraints
1 <= matrix.length <= 3001 <= matrix[0].length <= 3000 <= matrix[i][j] <= 1
Constraints that matter
- The grid can hold 90,000 cells, so you need roughly one unit of work per cell. Any method that re-reads every cell of each candidate square is too slow.
- Each cell's answer depends only on its top, left and top-left neighbours. That locality lets a single pass compute everything.
- The answer can reach about 9 * 10^6 on an all-ones 300 by 300 grid, so a plain 32-bit integer is enough.
- Values are only 0 or 1, so you can test a cell with a simple equality check and never worry about other values.
Hints
Hint 1
The problem asks you to count squares, but squares nest inside each other.
Hint 2
Treat every cell as a possible top-left corner.
Solution
Intuition
The problem asks you to count squares, but squares nest inside each other. A 3 by 3 block of ones holds four 2 by 2 squares and nine 1 by 1 squares. Any method that counts squares by their top-left corner repeats that nesting work again and again.
Picture a grid of nested picture frames where each cell's dp value is how many square frames end at that spot. Adding up those counts gives the total number of squares, with each one counted once.
This is a dynamic programming problem on a grid, the same shape as Unique Paths. Each cell's answer depends only on its top, left and top-left neighbours. Ask a different question for each cell: what is the largest all-ones square whose bottom-right corner is this cell?
The neighbours decide the answer. A side-k square ending at (i, j) is a side-(k-1) square ending at (i-1, j-1) plus an L-shaped strip of its last row and last column. The strip must be all ones.
The squares of side k-1 ending at (i-1, j) and (i, j-1) must cover that strip, so the smallest of the three neighbour values sets the limit. Adding one gives this cell's value.
Once the table holds these values, counting is direct. A cell with value v is the bottom-right corner of exactly v squares, with sides 1 through v. Summing the table counts every square once.
Worked example
Input: matrix = [[1,0,1],[1,1,0],[1,1,0]] Output: 7 Explanation: Row 0 has 1s at columns 0 and 2, and rows 1 and 2 each have 1s at columns 0 and 1, giving six single-cell squares. The only 2 by 2 all-ones square sits at rows 1 to 2 and columns 0 to 1. The total is 6 + 1 = 7.
Approach 1: Brute force
Treat every cell as a possible top-left corner. From each corner, try side lengths 1, 2, 3 and so on. Stop growing once the square leaves the grid or contains a 0. Most people write this first, and it is correct.
What's slow: the check reads every cell again for each size. A 3 by 3 check reads nine cells, including the four cells of a 2 by 2 square that the previous size already verified. Each larger square repeats the work of the smaller squares inside it, so the same cells are read many times.
Steps
- Loop over every cell (i, j) as a candidate top-left corner.
- Set k = 1 and check whether a k by k square starting at (i, j) fits inside the matrix.
- Scan all k * k cells of that square. If any cell is 0, stop growing from this corner.
- If the square is all ones, add 1 to the total and increase k by 1.
- When the square no longer fits or hits a 0, move to the next corner. Return the total after the last corner.
Dry run
Walk the corners in row-major order on the example matrix [[1,0,1],[1,1,0],[1,1,0]].
- Corner (0,0): k = 1 covers one cell with value 1. Total becomes 1. k = 2 covers rows 0 to 1 and columns 0 to 1, which includes the 0 at (0,1). Stop.
- Corner (0,1): the cell is 0, so skip it.
- Corner (0,2): k = 1 gives total 2. k = 2 would need column 3, which does not exist. Stop.
- Corner (1,0): k = 1 gives total 3. k = 2 covers rows 1 to 2 and columns 0 to 1, which are all ones. Total becomes 4. k = 3 does not fit.
- Corner (1,1): k = 1 gives total 5. k = 2 covers rows 1 to 2 and columns 1 to 2, which includes 0s. Stop.
- Corner (1,2) and (2,2) hold 0. Corner (2,0): k = 1 gives total 6. k = 2 does not fit.
- Corner (2,1): k = 1 gives total 7. k = 2 does not fit.
The trace ends at 7, which matches the expected output.
Complexity
| Time | O(m * n * min(m, n)^3) |
|---|---|
| Space | O(1) |
Let m and n be the matrix dimensions, and let s = min(m, n). There are m * n possible top-left corners. For each corner, the loop tries side lengths up to s, and the check for side k reads k * k cells. Summing k * k up to s gives about s^3 / 3 reads per corner, so the total is O(m * n * s^3), and the algorithm stores only a few integers, so the extra space is O(1).
PythonTested in our runner
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
rows = len(matrix)
cols = len(matrix[0])
total = 0
for i in range(rows):
for j in range(cols):
# Grow the square from (i, j) one side at a time
k = 1
while i + k <= rows and j + k <= cols:
ok = True
for r in range(i, i + k):
for c in range(j, j + k):
if matrix[r][c] == 0:
ok = False
if not ok:
break
total += 1
k += 1
return totalThe 2D Array (Unique Paths on Grid) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
2D Array (Unique Paths on Grid)
Approach 2: One-pass DP tableOptimal2D Array (Unique Paths on Grid)
What's slow: the brute force never remembers what it learned about smaller squares. It reads each cell once for every square that covers it.
The insight that fixes it: flip the question. Instead of asking how far a square reaches from each top-left corner, ask how large the biggest all-ones square is when it ends at each bottom-right corner. Store that side length as dp[i][j]. A cell with value v also counts v squares, so the answer is the sum of the table.
The recurrence is dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 when matrix[i][j] is 1. Cells in row 0 or column 0 can only end a side-1 square, so they hold 1. A cell that holds 0 ends no square, so its dp value stays 0.
Steps
- Create a dp table with the same shape as the matrix, filled with 0.
- Walk the cells in row-major order, from top to bottom and left to right.
- If matrix[i][j] is 0, leave dp[i][j] at 0 and move on.
- If the cell is in row 0 or column 0, set dp[i][j] = 1.
- Otherwise set dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1.
- Add dp[i][j] to the running total. Return the total after the last cell.
Dry run
Use the example matrix [[1,0,1],[1,1,0],[1,1,0]]. Each row shows one cell, the three neighbour values it reads, its dp value, and the running total.
| Cell | matrix | top | left | diag | dp | total |
|---|---|---|---|---|---|---|
| (0,0) | 1 | - | - | - | 1 | 1 |
| (0,1) | 0 | - | - | - | 0 | 1 |
| (0,2) | 1 | - | - | - | 1 | 2 |
| (1,0) | 1 | - | - | - | 1 | 3 |
| (1,1) | 1 | 0 | 1 | 1 | 1 | 4 |
| (1,2) | 0 | - | - | - | 0 | 4 |
| (2,0) | 1 | - | - | - | 1 | 5 |
| (2,1) | 1 | 1 | 1 | 1 | 2 | 7 |
| (2,2) | 0 | - | - | - | 0 | 7 |
Cell (1,1) reads a top value of 0, so the minimum is 0 and its dp value is 1. Cell (2,1) has all three neighbours at 1, so it reaches 2. That 2 counts two squares: the 2 by 2 square at rows 1 to 2 and columns 0 to 1, and the 1 by 1 square at (2,1). The final total is 7.
Complexity
| Time | O(m * n) |
|---|---|
| Space | O(m * n) |
Let m and n be the number of rows and columns. The double loop visits each cell exactly once, so there are m * n iterations. Each iteration does a fixed number of reads, one minimum over three values, and one addition. The dp table stores one integer per cell, so the extra space is O(m * n).
PythonTested in our runner
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
rows = len(matrix)
cols = len(matrix[0])
# dp[i][j] = side of the largest all-ones square with bottom-right corner (i, j)
dp = [[0] * cols for _ in range(rows)]
total = 0
for i in range(rows):
for j in range(cols):
if matrix[i][j] == 0:
continue
if i == 0 or j == 0:
dp[i][j] = 1
else:
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1
# dp[i][j] squares end at (i, j), one for each side length 1..dp[i][j]
total += dp[i][j]
return totalCommon mistakes
- Reading
dp[i-1][j]ordp[i][j-1]in the first row or column. Index -1 fails or wraps around in some languages. Handle row 0 and column 0 as base cases before the recurrence. - Using
min(top, left)and skipping the diagonal. A 0 in the top-left corner can then sit inside a square that the count treats as valid, so the answer is too high. Always includedp[i-1][j-1]. - Summing the matrix values instead of the dp values. Adding the original cells counts only 1 by 1 squares. Add
dp[i][j], which counts every square ending at that cell. - Walking the grid bottom-up or right-to-left. The recurrence reads the top and left neighbours, so those cells must already hold their final values when you reach the current cell.
- Leaving stale values in a reused dp table. Write 0 for zero cells explicitly, or allocate a fresh table, so an earlier value does not feed into a later minimum.
- Writing dp values into the input matrix and then reading the matrix again for a second pass. The overwritten cells no longer hold 0s and 1s, so the second pass counts the wrong cells.
Edge cases
- An all-zero matrix, such as
[[0,0],[0,0]]. Every dp value stays 0, so the answer is 0. - A single cell.
[[1]]returns 1 and[[0]]returns 0. - A single row such as
[[1,1,1]]. No square is taller than 1, so the answer is the count of ones, which is 3. - An all-ones 2 by 3 matrix. There are 6 squares of side 1 and 2 squares of side 2, so the answer is 8.
- A tall, narrow matrix such as 300 by 1. This checks that the loops use rows and columns separately and never assume a square grid.
- A 300 by 300 all-ones matrix. The answer is the sum of squares from 1 to 300, which is 9,045,050. That fits in a 32-bit integer.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Count Square Submatrices with All Ones, with how to answer them.
Unlock the follow-upsCount Square Submatrices with All Ones FAQ
What is the time complexity of Count Square Submatrices with All Ones?
The dynamic programming solution runs in O(m * n) time, because it visits each cell once and does constant work per cell. The brute force runs in O(m * n * min(m, n)^3), which is far too slow for a 300 by 300 matrix.
Why use dynamic programming for Count Square Submatrices with All Ones?
A square ending at a cell is built from squares ending at its three neighbours. Storing those answers lets every cell reuse them, so no square is checked from scratch. That reuse turns the cubic brute force into a single pass.
Can Count Square Submatrices with All Ones be solved in O(1) extra space?
Yes, but only by overwriting the input matrix with dp values, which destroys the original grid. If the input must stay intact, the best option is O(n) space with two rolling rows. Keeping the full table gives O(m * n) space.
How is this different from Maximal Square (LeetCode 221)?
The recurrence is the same. Maximal Square returns the largest dp value, which is the side of the biggest square. This problem returns the sum of all dp values, which counts every square.
Why take the minimum of three neighbours?
A side-k square at a cell needs side-(k-1) squares at the top, left and top-left neighbours. The smallest neighbour value is the largest side that all three support. Taking the minimum and adding one gives the exact largest side for the current cell.
Asked at
See which companies ask this — Pro
Related problems
- Unique Paths · same technique: 2D Array (Unique Paths on Grid)
- Interleaving String · same technique: 2D Array (Unique Paths on Grid)
- Minimum Path Sum · same technique: 2D Array (Unique Paths on Grid)
- Unique Paths II · same technique: 2D Array (Unique Paths on Grid)
- Maximal Square · same technique: 2D Array (Unique Paths on Grid)
- Triangle · same technique: 2D Array (Unique Paths on Grid)
- Distinct Subsequences · next harder, same pattern
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns