Maximal Square
Medium
Topics
Given an m x n binary grid filled with 0s and 1s, find the largest square containing only 1s and return its area.
On this judge the grid is given as integers rather than characters.
Example 1
The shaded block is the largest solid square of
1s, 2×2. The answer is its area, 4, not its side. A rectangle does not count — only squares.2D grid — one row per line.
Input: grid = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]] Output: 4 Explanation: The largest all-ones square has side 2, so the area is 4.
Example 2
Input: grid = [[0,1],[1,0]] Output: 1
Example 3
Input: grid = [[0]] Output: 0
Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is 0 or 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Anchor each square at its bottom-right corner. A square of side k ending at a cell requires three overlapping squares of side k-1 ending at the cells above, to the left, and diagonally up-left. So the largest side you can anchor at a cell is one more than the smallest of those three - which turns a search over all squares into a single pass.
Approach
- Let
dp[i][j]be the side length of the largest all-ones square whose bottom-right corner is(i, j). - If
grid[i][j] == 0thendp[i][j] = 0- no square can end here. - Otherwise
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]). - Track the maximum side seen and return its square. Cells in row 0 or column 0 are capped at 1 by the recurrence itself if you pad the table with a zero border.
class Solution:
def maximalSquare(self, grid):
m, n = len(grid), len(grid[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
best = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if grid[i - 1][j - 1] == 1:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
best = max(best, dp[i][j])
return best * bestDry Run
grid 1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Each cell holds the SIDE of the largest square whose bottom-right corner is there.
Only the previous row is kept.
row 0 sides [1, 0, 1, 0, 0] best side 1
row 1 sides [1, 0, 1, 1, 1] best side 1
row 2 sides [1, 1, 1, 2, 2] best side 2
row 3 sides [1, 0, 0, 1, 0] best side 2
answer 2 * 2 = 4
Row 2 is where a square first appears. The cell at row 2, column 4 becomes 2
because its three neighbours -- above, left, and diagonal -- are all at least 1,
so a 2x2 block of ones is complete. Note row 1 column 4 is only 1 even though
there are ones to its left: a square needs height as well as width.
The min is over three neighbours, not two. Drop the one directly above and the
recurrence can claim a square with a hole in it: this grid then returns 9,
asserting a 3x3 square that does not exist.
And the answer is the AREA. Returning best gives 2 rather than 4 -- an easy
mistake precisely because the table itself stores sides.
Padding the row with an extra leading zero removes every boundary case. Column 0
of the padded array is permanently 0, so `cur[c-1]` at c=1 needs no branch.Complexity
- Time — O(m x n) — one pass, constant work per cell.
- Space — O(m x n) — the padded table; reducible to O(n) with a rolling row plus one saved diagonal.
Common Pitfalls
- Return the area, not the side length. Squaring at the end is easy to forget.
- The
minis over three neighbours, not two. Dropping the diagonal lets you claim squares with a hole in them. - Padding the table with an extra zero row and column removes every boundary special case - do that rather than writing branches for i == 0.
- Compare with Maximal Rectangle, where the square recurrence no longer applies and you need a monotonic stack instead.
Full Solution — all languages
class Solution:
def maximalSquare(self, grid):
rows, cols = len(grid), len(grid[0])
prev = [0] * (cols + 1)
best = 0
for r in range(rows):
cur = [0] * (cols + 1)
for c in range(1, cols + 1):
if grid[r][c - 1] == 1:
cur[c] = 1 + min(prev[c], prev[c - 1], cur[c - 1])
best = max(best, cur[c])
prev = cur
return best * bestimport java.util.*;
class Solution {
public int maximalSquare(int[][] grid) {
int rows = grid.length, cols = grid[0].length;
int[] prev = new int[cols + 1];
int best = 0;
for (int r = 0; r < rows; r++) {
int[] cur = new int[cols + 1];
for (int c = 1; c <= cols; c++) {
if (grid[r][c - 1] == 1) {
cur[c] = 1 + Math.min(Math.min(prev[c], prev[c - 1]), cur[c - 1]);
best = Math.max(best, cur[c]);
}
}
prev = cur;
}
return best * best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maximalSquare(vector<vector<int>>& grid) {
int rows = grid.size(), cols = grid[0].size();
vector<int> prev(cols + 1, 0), cur(cols + 1, 0);
int best = 0;
for (int r = 0; r < rows; r++) {
fill(cur.begin(), cur.end(), 0);
for (int c = 1; c <= cols; c++) {
if (grid[r][c - 1] == 1) {
cur[c] = 1 + min(min(prev[c], prev[c - 1]), cur[c - 1]);
best = max(best, cur[c]);
}
}
prev = cur;
}
return best * best;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var maximalSquare = function(grid) {
const rows = grid.length, cols = grid[0].length;
let prev = new Array(cols + 1).fill(0);
let best = 0;
for (let r = 0; r < rows; r++) {
const cur = new Array(cols + 1).fill(0);
for (let c = 1; c <= cols; c++) {
if (grid[r][c - 1] === 1) {
cur[c] = 1 + Math.min(prev[c], prev[c - 1], cur[c - 1]);
best = Math.max(best, cur[c]);
}
}
prev = cur;
}
return best * best;
};