221. Maximal Square
Asked at 25Apple51Google51Amazon33Meta31Microsoft30Bloomberg14eBay71GSA Capital100Wise88PayPal77Qualtrics69Airbnb66Karat65PhonePe64Whatnot63Zomato62ByteDance59Booking.com50Oracle49Nvidia48DE Shaw47Flipkart43Salesforce35TikTok35Goldman Sachs28
Problem
Given a binary matrix of '0'/'1' characters, return the area of the largest square containing only '1's.
Example: ["10100","10111","11111","10010"] → 4
Constraints: up to 300 × 300.
dp[r][c] = side of the largest all-1 square with bottom-right at (r, c) = 1 + min(top, left, top-left).
1 0 1 0 0 1 0 1 0 0
1 0 1 1 1 dp 1 0 1 1 1
1 1 1 1 1 -> 1 1 1 2 2 max side 2 -> area 4
1 0 0 1 0 1 0 0 1 0
Complexity: O(m·n).
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
n = len(matrix[0])
dp, best = [0] * (n + 1), 0
for row in matrix:
diag = 0 # dp[r-1][c-1]
for c in range(1, n + 1):
up = dp[c]
dp[c] = 1 + min(dp[c], dp[c - 1], diag) if row[c - 1] == "1" else 0
diag = up
best = max(best, dp[c])
return best * best
M = ["10100", "10111", "11111", "10010"]
assert Solution().maximalSquare([list(r) for r in M]) == 4
assert Solution().maximalSquare([["0"]]) == 0
class Solution {
public int maximalSquare(char[][] matrix) {
int n = matrix[0].length, best = 0;
int[] dp = new int[n + 1];
for (char[] row : matrix) {
int diag = 0;
for (int c = 1; c <= n; c++) {
int up = dp[c];
dp[c] = row[c - 1] == '1' ? 1 + Math.min(diag, Math.min(dp[c], dp[c - 1])) : 0;
diag = up;
best = Math.max(best, dp[c]);
}
}
return best * best;
}
}
func maximalSquare(matrix [][]byte) int {
n := len(matrix[0])
dp, best := make([]int, n+1), 0 // dp[c] = side of the largest square ending at (r, c-1)
for _, row := range matrix {
diag := 0 // dp[r-1][c-1]
for c := 1; c <= n; c++ {
up := dp[c]
if row[c-1] == '1' {
dp[c] = 1 + min(dp[c], dp[c-1], diag)
} else {
dp[c] = 0
}
diag = up
best = max(best, dp[c])
}
}
return best * best
}