KatInterview

221. Maximal Square

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the area of the largest square composed entirely of '1's in a given m x n binary matrix. A brute-force approach, checking every possible square, would be too inefficient given the constraints (m, n <= 300).

Solution

Maximal Square in Python

class Solution:
    def maximalSquare(self, matrix: list[list[str]]) -> int:
        if not matrix or not matrix[0]:
            return 0
        
        m, n = len(matrix), len(matrix[0])
        # dp array represents the DP values of the previous row.
        dp = [0] * (n + 1)
        max_side = 0
        
        # Loop through the matrix, considering each cell as a potential bottom-right corner.
        for i in range(1, m + 1):
            # prev stores the value of dp[i-1][j-1]. Reset for each new row.
            prev = 0
            for j in range(1, n + 1):
                # temp stores the old dp[j] value, which is dp[i-1][j].
                temp = dp[j]
                if matrix[i - 1][j - 1] == '1':
                    # Current dp[j] is dp[i-1][j] from the previous row.
                    # Current dp[j-1] is dp[i][j-1] from the current row (already updated).
                    # prev is dp[i-1][j-1].
                    dp[j] = min(dp[j], dp[j - 1], prev) + 1
                    max_side = max(max_side, dp[j])
                else:
                    dp[j] = 0
                # Update prev for the next iteration in this row.
                prev = temp
        
        return max_side * max_side

Maximal Square in Java

class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }

        int m = matrix.length;
        int n = matrix[0].length;
        // dp array represents the DP values of the previous row.
        int[] dp = new int[n + 1];
        int maxSide = 0;

        // Loop through the matrix, considering each cell as a potential bottom-right corner.
        for (int i = 1; i <= m; i++) {
            // prev stores the value of dp[i-1][j-1]. Reset for each new row.
            int prev = 0;
            for (int j = 1; j <= n; j++) {
                // temp stores the old dp[j] value, which is dp[i-1][j].
                int temp = dp[j];
                if (matrix[i - 1][j - 1] == '1') {
                    // Current dp[j] is dp[i-1][j] from the previous row.
                    // Current dp[j-1] is dp[i][j-1] from the current row (already updated).
                    // prev is dp[i-1][j-1].
                    dp[j] = Math.min(Math.min(dp[j], dp[j - 1]), prev) + 1;
                    maxSide = Math.max(maxSide, dp[j]);
                } else {
                    dp[j] = 0;
                }
                // Update prev for the next iteration in this row.
                prev = temp;
            }
        }

        return maxSide * maxSide;
    }
}

Maximal Square in C++

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) {
            return 0;
        }

        int m = matrix.size();
        int n = matrix[0].size();
        // dp array represents the DP values of the previous row.
        vector<int> dp(n + 1, 0);
        int max_side = 0;

        // Loop through the matrix, considering each cell as a potential bottom-right corner.
        for (int i = 1; i <= m; ++i) {
            // prev stores the value of dp[i-1][j-1]. Reset for each new row.
            int prev = 0; 
            for (int j = 1; j <= n; ++j) {
                // temp stores the old dp[j] value, which is dp[i-1][j].
                int temp = dp[j];
                if (matrix[i - 1][j - 1] == '1') {
                    // Current dp[j] is dp[i-1][j] from the previous row.
                    // Current dp[j-1] is dp[i][j-1] from the current row (already updated).
                    // prev is dp[i-1][j-1].
                    dp[j] = min({dp[j], dp[j - 1], prev}) + 1;
                    max_side = max(max_side, dp[j]);
                } else {
                    dp[j] = 0;
                }
                // Update prev for the next iteration in this row.
                prev = temp;
            }
        }

        return max_side * max_side;
    }
};

Maximal Square in TypeScript

function maximalSquare(matrix: string[][]): number {
    if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
        return 0;
    }

    const m = matrix.length;
    const n = matrix[0].length;
    // dp array represents the DP values of the previous row.
    const dp: number[] = new Array(n + 1).fill(0);
    let maxSide = 0;

    // Loop through the matrix, considering each cell as a potential bottom-right corner.
    for (let i = 1; i <= m; i++) {
        // prev stores the value of dp[i-1][j-1]. Reset for each new row.
        let prev = 0;
        for (let j = 1; j <= n; j++) {
            // temp stores the old dp[j] value, which is dp[i-1][j].
            const temp = dp[j];
            if (matrix[i - 1][j - 1] === '1') {
                // Current dp[j] is dp[i-1][j] from the previous row.
                // Current dp[j-1] is dp[i][j-1] from the current row (already updated).
                // prev is dp[i-1][j-1].
                dp[j] = Math.min(dp[j], dp[j - 1], prev) + 1;
                maxSide = Math.max(maxSide, dp[j]);
            } else {
                dp[j] = 0;
            }
            // Update prev for the next iteration in this row.
            prev = temp;
        }
    }

    return maxSide * maxSide;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.