




Sponsored
Sponsored
In this approach, a dynamic programming (DP) table is used to store the size of the largest square whose bottom-right corner is at each cell. For each cell (i, j) with a value of '1', we check its top (i-1, j), left (i, j-1), and top-left (i-1, j-1) neighbors to determine the size of the largest square ending at (i, j). If any of these neighbors are '0', the square cannot extend to include (i, j). The formula is: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1. The maximum value in the DP table will be the side length of the largest square, and the area is its square.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(m * n), due to the DP table.
1var maximalSquare = function(matrix) {
2    if (matrix.length === 0) return 0;
3    const m = matrix.length;
4    const n = matrix[0].length;
5    const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
6    let maxSide = 0;
7    for (let i = 1; i <= m; i++) {
8        for (let j = 1; j <= n; j++) {
9            if (matrix[i - 1][j - 1] === '1') {
10                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;
11                maxSide = Math.max(maxSide, dp[i][j]);
12            }
13        }
14    }
15    return maxSide * maxSide;
16};The JavaScript solution uses nested arrays initiated via Array.from to create the DP table, applying standard JS Math functions to check each cell in a nested loop, similar to other solutions, aiming to find the maximal square.
This approach uses a similar DP strategy but optimizes space by utilizing a one-dimensional array instead of a full 2D DP table. The key idea is that while processing the matrix row by row, previous rows' information will be partially redundant. Hence, we can maintain only the current and previous row data in separate arrays or even use a single array with swap states.
Time Complexity: O(m * n)
Space Complexity: O(n)
1The Java solution utilizes one-dimensional arrays for space efficiency, similar in spirit to the C++ version. Advantages include an effective space reduction because only linear elements of length `n` are created for use at any single time.