1277. Count Square Submatrices with All Ones
mediumGiven a 0/1 matrix, count all square submatrices entirely of 1s. The classic 'max square at (i, j)' DP doubles as a counter — sum every cell's largest-square value.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Constraints
1 <= arr.length <= 3001 <= arr[0].length <= 3000 <= arr[i][j] <= 1
Examples
Example 1
matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]15Explanation: There are 10 squares of side 1, 4 squares of side 2, 1 square of side 3. Total = 15.
Example 2
matrix = [[1,0,1],[1,1,0],[1,1,0]]7Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
If dp[i][j] = side length of the largest all-1 square with bottom-right corner at (i, j), that's also the count of squares ending at (i, j).
Hint 2
Recurrence on 1-cells: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]).
Hint 3
Answer = sum of dp[i][j] over the whole grid.
Solution approach
Reveal approach
Define the subproblem dp[i][j] = the side length of the largest all-1 square whose bottom-right corner is (i, j). This value equals the number of distinct squares ending at that corner (one of each side from 1 up to dp[i][j]). The recurrence relation is dp[i][j] = 0 if matrix[i][j] == 0, else 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) — a square of side s ending here requires that s-1 squares exist above, left, and on the diagonal. Base case: cells in row 0 or column 0 with matrix[i][j] == 1 contribute dp[i][j] = 1. Sum dp over the whole grid for the answer. You can update the matrix in place to save memory, or roll two rows. O(m * n) time, O(m * n) or O(min(m, n)) space.
Complexity
- Time
- O(m * n)
- Space
- O(m * n)
Related patterns
- dynamic-programming
- memoization-recursion
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
More Dynamic Programming practice problems
- 62. Unique Paths
- 70. Climbing Stairs
- 72. Edit Distance
- 91. Decode Ways
- 96. Unique Binary Search Trees
- 118. Pascal's Triangle
- 120. Triangle
- 122. Best Time to Buy and Sell Stock II