Maximal Square (LeetCode 221): Solution and Explanation
You get a grid of 0 and 1 characters and need the area of the largest square sub-grid made up entirely of 1s.
Watch it run step by step
Try your own input and write the code →Intuition
A brute force treats every cell as a possible top-left corner and keeps growing the square while the new row and column are all 1s. In the worst case that is O((m × n)²), since each of the m × n corners can check up to min(m, n)² cells. The repeated work is obvious: neighboring corners keep re-checking the same cells.
Flip the viewpoint and ask, for each cell, how big a square of 1s can have this cell as its bottom-right corner. Call that dp[i][j]. If the cell is 0, the answer is 0. If it is 1, a square of side s ending here requires squares of side s - 1 ending at the cell above, the cell to the left and the cell diagonally up-left. The weakest of those three neighbors limits you, so dp[i][j] = min(top, left, diagonal) + 1.
It helps to picture why all three neighbors are needed. The top neighbor guarantees the column above is filled, the left neighbor guarantees the row to the left, and the diagonal guarantees the interior. If any one of them is short, a corner of the larger square would be missing a 1. The answer is the largest side found anywhere, squared. Padding the DP table with an extra row and column of zeros removes all boundary checks.
Notice that the DP value is a side length, not an area. That keeps the recurrence additive and simple, and you only square the best side once at the very end.
Approach: Bottom-right corner dynamic programming
- Return 0 for an empty matrix.
- Create a
(rows + 1) × (cols + 1)table of zeros so row 0 and column 0 act as padding. - Loop
ifrom 1 to rows andjfrom 1 to cols, mapping tomatrix[i - 1][j - 1]. - If that cell is '1', set
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1. - Track
max_side, the largest value written. - Return
max_side * max_side, the area.
Step-by-step example
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
- Row 1 of the matrix just copies its 1s: DP values
[1, 0, 1, 0, 0]. - Row 2 gives
[1, 0, 1, 1, 1]. Each 1 has at least one zero among its three neighbors, so nothing exceeds side 1. - Row 3: the fourth column sees top 1, left 1 and diagonal 1, so it becomes 2. The fifth column sees top 1, left 2 and diagonal 1, so it is 2 as well. The row is
[1, 1, 1, 2, 2]andmax_side = 2. - Row 4: only the fourth column is a 1 with neighbors top 2, left 0 and diagonal 1, so it gets 1.
- The largest side is 2, so the area is 4.
Code: Python, Java, C++
1class Solution:
2 def maximalSquare(self, matrix: List[List[str]]) -> int:
3 if not matrix or not matrix[0]:
4 return 0
5
6 rows, cols = len(matrix), len(matrix[0])
7 dp = [[0] * (cols + 1) for _ in range(rows + 1)]
8 max_side = 0
9
10 for i in range(1, rows + 1):
11 for j in range(1, cols + 1):
12 if matrix[i-1][j-1] == '1':
13 dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
14 max_side = max(max_side, dp[i][j])
15
16 return max_side * max_side1class Solution {
2 public int maximalSquare(char[][] matrix) {
3 if (matrix == null || matrix.length == 0) return 0;
4
5 int rows = matrix.length, cols = matrix[0].length;
6 int[][] dp = new int[rows + 1][cols + 1];
7 int maxSide = 0;
8
9 for (int i = 1; i <= rows; i++) {
10 for (int j = 1; j <= cols; j++) {
11 if (matrix[i-1][j-1] == '1') {
12 dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1;
13 maxSide = Math.max(maxSide, dp[i][j]);
14 }
15 }
16 }
17 return maxSide * maxSide;
18 }
19}1class Solution {
2public:
3 int maximalSquare(vector<vector<char>>& matrix) {
4 if (matrix.empty() || matrix[0].empty()) return 0;
5
6 int rows = matrix.size(), cols = matrix[0].size();
7 vector<vector<int>> dp(rows + 1, vector<int>(cols + 1, 0));
8 int maxSide = 0;
9
10 for (int i = 1; i <= rows; i++) {
11 for (int j = 1; j <= cols; j++) {
12 if (matrix[i-1][j-1] == '1') {
13 dp[i][j] = min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]}) + 1;
14 maxSide = max(maxSide, dp[i][j]);
15 }
16 }
17 }
18 return maxSide * maxSide;
19 }
20};Time and space complexity
O(m × n)
Each cell is filled once using three lookups.
O(m × n)
The padded DP table has (m + 1) × (n + 1) entries.
Other approaches
Rolling one-row DP (time O(m × n), space O(n))
Keep only the previous row (or a single row plus one variable for the diagonal), since each cell only looks one row up. Same time with less memory.
Brute force square growth (time O((m × n)²), space O(1))
From every 1, expand the square while the next row and column are all 1s. Easy to write, far too slow for large grids.
Common mistakes
- Comparing cells with the integer 1 when the grid holds the character '1' makes every cell look like a 0.
- Returning
max_sideinstead of its square returns the side length, not the area. - Using only the top and left neighbors misses holes in the diagonal interior, so an L shape is counted as a square.
- Indexing
dp[i - 1]without padding at i = 0 reads the last row in Python and gives wrong values instead of an error.
Frequently asked questions
Why take the minimum of three neighbors?
A square of side s ending at a cell needs squares of side s - 1 ending above, to the left and diagonally. The smallest of the three is the bottleneck, so the new square can only be one larger than it.
Why does the DP table have an extra row and column?
The padding acts as a border of zeros, so cells in the first row and column can use the same formula without special boundary checks.
Can maximal square be solved in O(n) space?
Yes. Each row depends only on the row above, so a single array of size cols + 1 plus one saved diagonal value is enough.
How is this different from maximal rectangle?
Rectangles do not have the neat three-neighbor property, so maximal rectangle uses per-row histograms and the largest rectangle in histogram stack technique instead.