Maximal Square - Problem
Find the Largest Square of 1s in a Binary Matrix
You're given an
Think of this matrix as a grid where
Example:
The largest square of
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
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
โ Linear Growth
Space Complexity
O(mรn)
DP table of same size as input matrix (can be optimized to O(n))
โก Linearithmic Space
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 โค m, n โค 300
- matrix[i][j] is '0' or '1'
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code