Maximal Square - Problem
Find the Largest Square of 1s in a Binary Matrix

You're given an m x n binary matrix filled with 0s and 1s. Your task is to find the largest square that contains only 1s and return its area.

Think of this matrix as a grid where 1 represents a solid block and 0 represents empty space. You need to find the biggest perfect square you can form using only the solid blocks.

Example:
[[1,0,1,0,0],
[1,0,1,1,1],
[1,1,1,1,1],
[1,0,0,1,0]]


The largest square of 1s has side length 2, so the answer is 4 (area = 2 ร— 2).

Input & Output

example_1.py โ€” Basic Square
$ Input: [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
โ€บ Output: 4
๐Ÿ’ก Note: The largest square of 1s has side length 2 (in rows 1-2, cols 2-3), so area = 2ร—2 = 4
example_2.py โ€” Single Cell
$ Input: [["0","1"],["1","0"]]
โ€บ Output: 1
๐Ÿ’ก Note: The largest square of 1s has side length 1 (any single '1'), so area = 1ร—1 = 1
example_3.py โ€” No Squares
$ Input: [["0"]]
โ€บ Output: 0
๐Ÿ’ก Note: No 1s in the matrix, so no square can be formed, area = 0

Visualization

Tap to expand
Dynamic Programming Formuladp[i-1][j-1]dp[i-1][j]dp[i][j-1]dp[i][j]dp[i][j] = min(โ†–, โ†‘, โ†) + 1These three values determinethe largest square endingat the current position
Understanding the Visualization
1
Start with Basics
First row and column squares can only be size 1 if the cell contains '1'
2
Build from Previous
For any other cell, look at the three neighbors (left, top, diagonal) and take the minimum square size found there
3
Add Current Block
If current cell is '1', add 1 to the minimum neighbor value. This gives you the largest square ending at current position
4
Track Maximum
Keep track of the largest square side found throughout the process
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking every possible square from scratch, we build the solution incrementally by remembering what we've computed before. Each cell's answer depends on just three previously computed neighbors, making this an elegant O(mn) solution.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(mร—n)

Single pass through all cells in the matrix, constant work per cell

n
2n
โœ“ Linear Growth
Space Complexity
O(mร—n)

DP table of same size as input matrix (can be optimized to O(n))

n
2n
โšก Linearithmic Space

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 โ‰ค m, n โ‰ค 300
  • matrix[i][j] is '0' or '1'
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
68.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen