Count All-One Square Submatrices
PurestorageSoftware Engineer · Technical ScreenLast updated
Tests dynamic programming and 2D grid traversal skills by counting the total number of square submatrices filled entirely with ones.
Problem Statement
Given an m x n binary matrix grid containing only 0s and 1s, return the total number of square submatrices that are composed entirely of 1s.
A square submatrix is defined by choosing a top-left corner (r1, c1) and a bottom-right corner (r2, c2) such that r2 - r1 == c2 - c1.
Function Signature
def count_squares(grid: list[list[int]]) -> int:
pass
Input & Output Format
- Input: A 2D list of integers
gridof dimensionsm x n, where each element is either0or1. - Output: An integer representing the total count of square submatrices containing only
1s.
Constraints
1 <= m, n <= 300grid[i][j]is either0or1
Examples
Example 1
Input:
grid = [
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 1]
]
Output: 15
Explanation:
- 1x1 squares: 10
- 2x2 squares: 4
- 3x3 squares: 1
Total squares = 10 + 4 + 1 = 15.
Example 2
Input:
grid = [
[1, 0, 1],
[1, 1, 0],
[1, 1, 0]
]
Output: 7
Explanation:
- 1x1 squares: 6
- 2x2 squares: 1
Total squares = 6 + 1 = 7.
Edge Cases
- Matrix with dimensions
1 x 1(returns1ifgrid[0][0] == 1, else0). - Matrix consisting solely of
0s (returns0). - Matrix consisting solely of
1s. - Single-row or single-column matrices.
Hints
Hint 1
Consider defining dp[r][c] as the side length of the largest square submatrix whose bottom-right corner is located at (r, c).
Hint 2
Notice that if the largest square ending at (r, c) has side length k, it also contributes exactly k distinct square submatrices ending at (r, c).
Hint 3
For grid[r][c] == 1, dp[r][c] depends on the values of its top, left, and top-left neighbors: 1 + min(dp[r-1][c], dp[r][c-1], dp[r-1][c-1]).
Follow-up questions
- How would you optimize the auxiliary space complexity from O(m * n) down to O(n) or O(1)?
- How does the solution change if you are asked to count all rectangular submatrices of ones rather than just square ones?
- If the grid is too large to fit in memory and is partitioned into tiles across storage disks, how would you design an algorithm to count squares crossing tile boundaries?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.