Maximal Square – Solution & Complexity
Solution Walkthrough
Step 1: Start from what makes a square valid
- A square is only valid if every cell inside it is
1. - The answer asks for area, but it is easier to reason about side length first and square it at the end.
- That leads naturally to either expanding candidate squares or building a DP table of best side lengths.
- A square is only valid if every cell inside it is
Step 2: Brute force: expand from each top-left 1
- Treat each cell containing
1as a possible top-left corner. - Try to grow the square one layer at a time, checking the newly added bottom row and right column before accepting the larger side length.
- This works, but in the worst case it repeatedly rechecks many cells and costs
O(m*n*k^2)time wherek = min(m, n).
- Treat each cell containing
Step 3: Use DP for squares ending at each cell
- Let
dp[r][c]be the side length of the largest all-1square whose bottom-right corner is(r, c). - If
matrix[r][c]is0, thendp[r][c] = 0. - Otherwise, border cells can only form a
1x1square, and interior cells extend the smallest of the three neighboring squares: top, left, and top-left diagonal.
- Let
Step 4: Optimal solution: dynamic programming in one pass
- Sweep the matrix row by row.
- When
matrix[r][c] == 1, computedp[r][c] = 1 + min(dp[r-1][c], dp[r][c-1], dp[r-1][c-1])for interior cells, or1on the first row/column. - Track the largest side length seen, then return its square as the area. This runs in
O(m*n)time andO(m*n)space.