SDE & MLE Prep

221. Maximal Square

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