Maximal Square

35 min · maximalSquare()

A cluster of active seats matters only when it forms a solid square—one empty seat breaks the whole block.

You're given a rectangular binary matrix, a grid whose cells are the one-character strings "0" and "1". Return the area of the largest all-ones square whose edges follow the grid's rows and columns.

The returned value is an area, not a side length. A square with side 3 contributes 3² = 9. If the matrix contains no "1", return 0.

A few ground rules:

  • Squares follow the matrix rows and columns; they aren't rotated.
  • Every cell inside the chosen square must be "1".
  • The matrix is rectangular, so every row has the same number of cells.

Constraints

  • 1 <= matrix.length <= 300
  • 1 <= matrix[i].length <= 300
  • Every row has the same length.
  • Every cell is either "0" or "1".

Hints

Grow a candidate honestly

Pick a top-left corner and try side lengths 1, 2, 3, .... When growing by one, only the new bottom row and new right column need checking.

Change the corner you store

Instead of asking whether a top-left corner can grow, let each cell be the bottom-right corner of the largest all-ones square ending there.

Three neighbors set the limit

A "1" cell can extend a square only as far as its upper, left, and upper-left neighbors all allow. Its side is 1 + min(up, left, diagonal).

Follow-up

Could you also return the top-left and bottom-right coordinates of one largest square?

Visible cases

Examples

Example 1

ready
Input
matrix = [
  [
    "1",
    "0",
    "1",
    "0",
    "0"
  ],
  [
    "1",
    "0",
    "1",
    "1",
    "1"
  ],
  [
    "1",
    "1",
    "1",
    "1",
    "1"
  ],
  [
    "1",
    "0",
    "0",
    "1",
    "0"
  ]
]
Expected
4
Why
the largest all-ones square has side 2, so its area is 4

Example 2

ready
Input
matrix = [
  [
    "0",
    "0",
    "0"
  ],
  [
    "0",
    "0",
    "0"
  ]
]
Expected
0
Why
there is no all-ones square

Example 3

ready
Input
matrix = [
  [
    "1",
    "1"
  ],
  [
    "1",
    "1"
  ],
  [
    "1",
    "1"
  ]
]
Expected
4
Why
the shorter dimension is 2, giving a 2 × 2 square

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite