Count Square Submatrices with All Ones - Problem

You're given an m × n binary matrix containing only 0s and 1s. Your task is to count how many square submatrices contain all ones.

A square submatrix is a contiguous block of cells arranged in a square shape (same width and height). For example, in a 3×3 matrix, you could have 1×1, 2×2, or 3×3 square submatrices.

Goal: Return the total count of all square submatrices that contain only 1s.

Example: In matrix [[1,1],[1,1]], there are 5 valid squares: four 1×1 squares and one 2×2 square.

Input & Output

example_1.py — Basic 2×2 Matrix
$ Input: matrix = [[1,1],[1,1]]
Output: 5
💡 Note: There are 4 squares of size 1×1 and 1 square of size 2×2. Total = 4 + 1 = 5 squares.
example_2.py — Matrix with Zeros
$ Input: matrix = [[1,1,0],[1,1,1],[1,1,1]]
Output: 7
💡 Note: There are 6 squares of size 1×1 (only the 1s) and 1 square of size 2×2 (bottom-right). Total = 6 + 1 = 7 squares.
example_3.py — All Zeros
$ Input: matrix = [[0,0],[0,0]]
Output: 0
💡 Note: No squares can be formed with all ones since the matrix contains only zeros.

Visualization

Tap to expand
DP Table Construction111?Computing dp[1][1]:• Top: dp[0][1] = 1• Left: dp[1][0] = 1• Diagonal: dp[0][0] = 1min(1,1,1) + 1 = 2Key Insight: Each dp[i][j] counts all squares ending at (i,j)If dp[i][j] = 3, then there are 3 squares ending there:1×1, 2×2, and 3×3 squares
Understanding the Visualization
1
Start with base cases
First row and column can only have 1×1 squares
2
Look at neighbors
For any cell, check top, left, and diagonal neighbors
3
Find the bottleneck
The minimum of the three neighbors limits your square size
4
Add one more
If current cell is 1, you can extend the smallest neighbor square by 1
Key Takeaway
🎯 Key Insight: The number of squares ending at position (i,j) equals the side length of the largest square ending there!

Time & Space Complexity

Time Complexity
⏱️
O(m²n²)

For each of m×n positions, we check up to min(m,n) square sizes, and each check takes O(min(m,n)²) time

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track positions and counts

n
2n
Linear Space

Constraints

  • 1 ≤ matrix.length, matrix[i].length ≤ 300
  • matrix[i][j] is 0 or 1
  • The matrix is rectangular (all rows have same length)
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
89.2K Views
Medium-High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen