Skip to content
Problem 221 · LeetCode 221(opens in a new tab)

Maximal Square

MediumDynamic programming

You get an m × n grid matrix where every cell holds the character "0" or "1".

Find the biggest square made only of "1" cells and return its area, the number of cells inside it. If the grid has no "1" at all, return 0.

Example 1

Input:  matrix = [["1","1","0"],
                  ["1","1","1"],
                  ["0","1","1"]]
Output: 4
Why:    two 2×2 squares, but no 3×3
2 more examples and the constraints

Example 2

Input:  matrix = [["1","1","1","0"],
                  ["1","1","1","0"],
                  ["1","1","1","0"],
                  ["0","0","1","1"]]
Output: 9
Why:    the top-left 3×3 block is all 1s

Example 3

Input:  matrix = [["0","0"],["0","0"]]
Output: 0
Why:    there is no 1 to start a square

Constraints

  • 1 ≤ m, n ≤ 300
  • Each matrix[i][j] is "0" or "1".

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Grow a square from every cellO(m · n · k²)
  2. DP on the bottom-right cornerO(m · n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeCell checks on a 300 × 300 grid of 1sVerdict
Grow a square from every cellO(m · n · k²)
Too slow on large grids
DP on the bottom-right cornerO(m · n)
Best; one pass

m, n = grid size, k = min(m, n). The DP does about 90,000 steps where growing does over a billion.

Edge cases to test

  • No 1 at all. Return 0, not 1.
  • A single cell. [["1"]] has area 1; [["0"]] has area 0.
  • One row or one column. Any 1 gives a 1×1 square, so the answer is at most 1.
  • A wide rectangle of 1s. A 2 × 5 block of 1s gives 4, not 10. The shape must be a square.
  • Area, not side. The table stores sides; return the side squared.

Common mistakes

  • Returning the side length instead of the area.
  • Taking the max of the three neighbours instead of the min, which counts squares that have a 0 inside.
  • Comparing the cell to the number 1 instead of the character "1", so no cell ever matches.

How to talk through it

  1. 1Clarify. Confirm the cells are characters, that I return the area, and that the grid is never empty.
  2. 2Give the brute force. Grow a square from every corner, checking only the new ring. Say why it repeats work.
  3. 3Define the state. dp[i][j] is the side of the largest all-1 square whose bottom-right corner is (i, j).
  4. 4Explain the min rule. The square here is limited by the smallest of the top, left and diagonal squares.
  5. 5Test out loud. Run a grid of all 0s, a single 1, and a 2 × 5 block of 1s.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?