Maximal Rectangle - Problem
Imagine you're a city planner looking at a blueprint from above, where 1's represent buildable land and 0's represent water or restricted areas. Your task is to find the largest rectangular plot that can be built on, containing only buildable land (1's).
Given a rows ร cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example: In a matrix like [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]], the largest rectangle of 1's has area 6 (a 2ร3 rectangle).
Input & Output
example_1.py โ Standard Case
$
Input:
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
โบ
Output:
6
๐ก Note:
The maximal rectangle is formed by the 2ร3 rectangle in the bottom-right area, containing only 1's with area 6
example_2.py โ Single Row
$
Input:
matrix = [["1"]]
โบ
Output:
1
๐ก Note:
Single cell containing '1' forms a rectangle of area 1
example_3.py โ All Zeros
$
Input:
matrix = [["0","0"],["0","0"]]
โบ
Output:
0
๐ก Note:
No rectangle can be formed with only 1's since all cells contain 0's
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Land
Look at the blueprint where 1's are buildable land and 0's are restricted areas
2
Build Height Profile
For each row, measure how tall we could build at each column (consecutive 1's above)
3
Find Best Rectangle
Use smart measuring tools (monotonic stack) to efficiently find the largest rectangular plot
4
Compare All Options
Repeat for each row and keep track of the best rectangular plot found
Key Takeaway
๐ฏ Key Insight: Transform the 2D rectangle problem into multiple 1D histogram problems, then use a monotonic stack to efficiently solve each histogram in linear time.
Time & Space Complexity
Time Complexity
O(mn)
O(mn) to build heights + O(mn) for histogram processing (each element pushed/popped once)
โ Linear Growth
Space Complexity
O(n)
O(n) for heights array + O(n) for stack in worst case
โก Linearithmic Space
Constraints
- rows == matrix.length
- cols == matrix[i].length
- 1 โค rows, cols โค 200
- matrix[i][j] is '0' or '1'
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code