Maximal Rectangle (LeetCode 85): Solution and Explanation
Given a binary matrix of '0' and '1' characters, find the area of the largest rectangle made entirely of 1s. The rectangle must be axis-aligned and contiguous.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force fixes two corners and checks every cell in between, which is O(rows³ × cols³) without tricks and still around O(rows² × cols²) with prefix sums. That is far too slow even for moderate grids.
The breakthrough is to reduce the 2D problem to a 1D one you may already know. Pick any row as the floor. For each column, count how many consecutive 1s stand on top of each other ending at that row; that is a histogram. Every all-ones rectangle has some bottom row, and when you use that row as the floor, the rectangle is a rectangle under that histogram. So the answer is the best largest-rectangle-in-histogram result over all rows.
The heights update in constant time per cell: a '1' extends the column by one, a '0' resets it to zero. The histogram part uses a monotonic stack of indices with increasing heights. When a shorter bar arrives, every taller bar on the stack has found its right limit, and the index under it on the stack is its left limit, so its widest rectangle can be computed and the bar popped. A sentinel at the left (index -1) and a zero-height bar at the right end make sure every bar gets popped.
Approach: Row histograms with a monotonic stack
- Return 0 for an empty matrix. Allocate
heightsof lengthn + 1, where the extra last entry is always 0. - For each row, set
heights[i]toheights[i] + 1if the cell is'1', else 0. - Start a stack with
-1and scanifrom 0 ton, including the zero sentinel. - While
heights[i]is less than the height at the stack top, pop the top ash, compute widthi - stack[-1] - 1, and updatemax_areawithh * w. - Push
iand continue. The index -1 readsheights[-1], the trailing zero, so the bottom of the stack is never popped. - After every row, return
max_area.
Step-by-step example
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
- Row 0 gives heights
[1,0,1,0,0]and best area 1. Row 1 gives[2,0,2,1,1], where the last three columns form a 1 by 3 rectangle, so the best is 3. - Row 2 gives
[3,1,3,2,2]. Index 1 (height 1) pops index 0 for area 3. Index 3 (height 2) pops index 2 for area 3. - The sentinel at index 5 pops index 4 (height 2, width 1, area 2), then index 3 (height 2, width 5 - 1 - 1 = 3, area 6), then index 1 (height 1, width 5, area 5).
- Row 3 gives
[4,0,0,3,0], whose best is the height 4 column with area 4. - The overall maximum is 6, the 2 by 3 block in rows 1 and 2, columns 2 to 4.
Code: Python, Java, C++
1class Solution:
2 def maximalRectangle(self, matrix: List[List[str]]) -> int:
3 if not matrix or not matrix[0]:
4 return 0
5
6 n = len(matrix[0])
7 heights = [0] * (n + 1)
8 max_area = 0
9
10 for row in matrix:
11 for i in range(n):
12 heights[i] = heights[i] + 1 if row[i] == '1' else 0
13
14 # Largest rectangle in histogram
15 stack = [-1]
16 for i in range(n + 1):
17 while heights[i] < heights[stack[-1]]:
18 h = heights[stack.pop()]
19 w = i - stack[-1] - 1
20 max_area = max(max_area, h * w)
21 stack.append(i)
22
23 return max_area1class Solution {
2 public int maximalRectangle(char[][] matrix) {
3 if (matrix.length == 0 || matrix[0].length == 0) return 0;
4
5 int n = matrix[0].length;
6 int[] heights = new int[n + 1];
7 int maxArea = 0;
8
9 for (char[] row : matrix) {
10 for (int i = 0; i < n; i++) {
11 heights[i] = row[i] == '1' ? heights[i] + 1 : 0;
12 }
13
14 // Largest rectangle in histogram
15 Deque<Integer> stack = new ArrayDeque<>();
16 stack.push(-1);
17 for (int i = 0; i <= n; i++) {
18 while (stack.peek() != -1 && heights[i] < heights[stack.peek()]) {
19 int h = heights[stack.pop()];
20 int w = i - stack.peek() - 1;
21 maxArea = Math.max(maxArea, h * w);
22 }
23 stack.push(i);
24 }
25 }
26
27 return maxArea;
28 }
29}1class Solution {
2public:
3 int maximalRectangle(vector<vector<char>>& matrix) {
4 if (matrix.empty() || matrix[0].empty()) return 0;
5
6 int n = matrix[0].size();
7 vector<int> heights(n + 1, 0);
8 int maxArea = 0;
9
10 for (auto& row : matrix) {
11 for (int i = 0; i < n; i++) {
12 heights[i] = row[i] == '1' ? heights[i] + 1 : 0;
13 }
14
15 // Largest rectangle in histogram
16 stack<int> st;
17 st.push(-1);
18 for (int i = 0; i <= n; i++) {
19 while (st.top() != -1 && heights[i] < heights[st.top()]) {
20 int h = heights[st.top()]; st.pop();
21 int w = i - st.top() - 1;
22 maxArea = max(maxArea, h * w);
23 }
24 st.push(i);
25 }
26 }
27
28 return maxArea;
29 }
30};Time and space complexity
O(rows × cols)
Each row updates every height once, and the stack pass pushes and pops each index at most once, so every row costs O(cols).
O(cols)
The heights array and the stack are both proportional to the number of columns.
Other approaches
Left, right and height DP (time O(rows × cols), space O(cols))
Keep three arrays per column: the current height, the leftmost and rightmost boundaries where that height still fits. Update them row by row and compute (right - left) * height. Same bounds, no stack.
Width counting per cell (time O(rows² × cols), space O(rows × cols))
For each cell, store how many consecutive 1s end there in its row, then walk upward taking the minimum width to compute every rectangle with that cell as its bottom-right corner.
Common mistakes
- Forgetting to reset a column height to 0 on a
'0'. Heights must count consecutive 1s, not total 1s above. - Leaving out the trailing zero bar. Bars still on the stack at the end of a row would never be measured.
- Computing width as
i - popped_indexinstead ofi - stack[-1] - 1. The left limit is the bar below the popped one on the stack, not the popped bar itself. - Comparing against the integer 1 instead of the string
'1'. The matrix holds characters, so the check silently fails.
Frequently asked questions
How is Maximal Rectangle related to Largest Rectangle in Histogram?
Treat each row as the ground and the column heights of consecutive 1s as bars. The largest rectangle in each of those histograms, taken over all rows, is the answer.
What is the time complexity of Maximal Rectangle?
O(rows × cols). Each row takes linear time to update heights and linear time for the stack scan.
Why use a monotonic stack?
It keeps bars in increasing height, so when a shorter bar arrives you immediately know the left and right limits of each taller bar it pops.
Can Maximal Rectangle be solved with dynamic programming?
Yes. The left, right and height arrays approach is a DP that also runs in O(rows × cols) time and O(cols) space.