Maximal Square
Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #221
In a binary matrix of "0" and "1", find the largest square containing only "1"s and return its area.
Example
text
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1 → 4 (a 2×2 square)
1 0 0 1 0Hints
- Let
dp[r][c]be the side of the largest all-ones square whose bottom-right corner is (r, c). - It's limited by the squares ending above, to the left, and diagonally up-left.
Approach
dp[r][c] = 1 + min(dp[r−1][c], dp[r][c−1], dp[r−1][c−1]) if the cell is '1', otherwise 0.
Why the min? A k×k square ending at (r,c) needs (k−1)-squares ending at each of those three neighbors. The smallest of the three is the bottleneck. Track the max side and return side². With a rolling 1-D array (keeping the diagonal in a temporary), it's O(R·C) time and O(C) space.
The same recurrence counts all square submatrices (LeetCode 1277): sum the dp values.
Complexity
Time: O(R·C). Space: O(C).
Python solution
def maximalSquare(matrix):
C = len(matrix[0])
dp = [0] * (C + 1)
best = 0
for row in matrix:
diag = 0
for c in range(1, C + 1):
tmp = dp[c]
if row[c - 1] == '1':
dp[c] = 1 + min(dp[c], dp[c - 1], diag)
best = max(best, dp[c])
else:
dp[c] = 0
diag = tmp
return best * bestJavaScript solution
function maximalSquare(matrix) {
const R = matrix.length, C = matrix[0].length;
const dp = Array.from({ length: R + 1 }, () => new Array(C + 1).fill(0));
let best = 0;
for (let r = 1; r <= R; r++) for (let c = 1; c <= C; c++) {
if (matrix[r - 1][c - 1] === '1') {
dp[r][c] = 1 + Math.min(dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]);
best = Math.max(best, dp[r][c]);
}
}
return best * best;
}