The Maximal Square problem provides a 2D binary matrix filled with 0s and 1s. Your objective is to find the largest square sub-grid that contains only 1s and return its area. For example, if you find a block of all 1s, the returned area should be 9.
This is the textbook problem for teaching 2D Dynamic Programming. It is asked frequently because its optimal solution is incredibly elegant and requires very little code, but deducing the recurrence relation requires a strong grasp of geometric overlap and state caching. It separates candidates who brute-force solutions from those who understand spatial state accumulation in time.
This problem relies purely on a 2D Dynamic Programming pattern.
We define a DP matrix where dp[i][j] represents the side length of the maximum square whose bottom-right corner is at cell (i, j).
If matrix[i][j] is '1', the size of the square ending there is determined by its top, left, and top-left neighbors. If any of those neighbors have a 0, the current square cannot be larger than 1.
The recurrence relation is:
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
You keep track of the maximum value seen in the DP table, and the final area is max_len * max_len.
Matrix:
1 0 1 0
1 1 1 1
1 1 1 1
Let's build the DP table:
Row 0: [1, 0, 1, 0]
Row 1: [1, 1, 1, 1] -> Using formula: dp[1][1] is min(0, 1, 1) + 1 = 1. dp[1][2] is min(1, 1, 0) + 1 = 1. dp[1][3] is min(0, 1, 1) + 1 = 1.
Row 2:
dp[2][1]: min(1, 1, 1) + 1 = 2. (Square of size 2 ending here!)dp[2][2]: min(1, 1, 1) + 1 = 2.dp[2][3]: min(1, 1, 1) + 1 = 2.
The maximum value in the DP table is 2. The maximum area is .Candidates often attempt to solve this by searching for all possible top-left corners and expanding diagonally until they hit a zero, taking time. While faster than naive brute force, it's not optimal. Another common error when implementing the DP approach is forgetting to handle the first row and first column correctly, where i-1 or j-1 would result in out-of-bounds exceptions.
For the Maximal Square coding problem, practice optimizing the space complexity. Since calculating dp[i][j] only requires the current row and the previous row, you can reduce the space complexity to strictly by using a 1D array that overwrites itself as you move down the matrix. Mentioning this space optimization will severely impress your interviewer.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Path Sum | Medium | Solve | |
| Unique Paths II | Medium | Solve | |
| Minimum Falling Path Sum | Medium | Solve | |
| Maximum Number of Points with Cost | Medium | Solve | |
| Count Square Submatrices with All Ones | Medium | Solve |