Skip to problem
←

Maximal Square

Medium 0 attempts

Given a matrix containing the characters "0" and "1", find the largest square made entirely of "1" cells. Its sides must follow the grid: choose consecutive rows and consecutive columns without skipping cells.

Return its area, not its coordinates or side length. A square must have equal height and width. If there are no "1" cells, return 0.

Function contract

Implement maximalSquare(matrix). Receive a nonempty rectangular matrix of string characters "0" and "1", not numeric values.

Output: Return the area of the largest all-ones square, or 0 if no cell contains "1".

Example 1

Input
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output
4

Example 2

Input
matrix = [["0","1"],["1","0"]]
Output
1
Visual Aid
Largest square in Example 1
Highlighted square has area 4101001011111111100102 × 2 = 4 cellsReturn 4Every enclosed cell contains "1".

The outlined region spans two rows and 2 columns. Its area is 4.

Constraints
  • 1 <= m, n <= 300
  • matrix[i][j] is '0' or '1'

Approach: Dynamic Programming

Using a padded table, dp[i][j] represents the side length of the largest square whose bottom-right corner is at matrix cell (i-1,j-1). If matrix[i-1][j-1] is '1', dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1. The answer is the maximum dp value squared.

javascript
function maximalSquare(matrix) {
  const m = matrix.length, n = matrix[0].length;
  const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));
  let max = 0;
  for (let i = 1; i <= m; i++)
    for (let j = 1; j <= n; j++)
      if (matrix[i-1][j-1] === "1") {
        dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;
        max = Math.max(max, dp[i][j]);
      }
  return max * max;
}

Time Complexity: O(m × n)

Space Complexity: O(m × n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript