Algo-Sim › Stacks & Monotonic Stack
Maximal Rectangle
Hard · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Largest all-1 rectangle in a 0/1 matrix: each row is the floor of a histogram of 1-runs, solved with Largest Rectangle in Histogram's stack.
Problem
You are given a rows × cols binary matrix of "0" and "1" characters. Return the area of the largest rectangle containing only "1"s.
Constraints
- 1 ≤ rows, cols ≤ 200
- matrix[r][c] is "0" or "1"
- Trying every pair of corners is O(rows² · cols²)
Edge cases to test
- All zeros:
0 - All ones: rows × cols
- A single row
Follow-up questions
- What about the largest square?
- A DP:
dp[i][j] = 1 + min(top, left, top-left)(LC 221): O(mn). - What is the cost?
- O(m·n): each row’s histogram updates in O(n) and the stack pass is O(n).
Solution
Java
public int maximalRectangle(char[][] matrix) {
int cols = matrix[0].length, best = 0;
int[] heights = new int[cols];
for (char[] row : matrix) {
for (int c = 0; c < cols; c++)
heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= cols; i++) {
int h = (i == cols) ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peek()] >= h) {
int height = heights[stack.pop()];
int left = stack.isEmpty() ? -1 : stack.peek();
best = Math.max(best, height * (i - left - 1));
}
stack.push(i);
}
}
return best;
}Python
def maximal_rectangle(matrix):
cols, best = len(matrix[0]), 0
heights = [0] * cols
for row in matrix:
for c in range(cols):
heights[c] = heights[c] + 1 if row[c] == "1" else 0
stack = []
for i in range(cols + 1):
h = 0 if i == cols else heights[i]
while stack and heights[stack[-1]] >= h:
height = heights[stack.pop()]
left = stack[-1] if stack else -1
best = max(best, height * (i - left - 1))
stack.append(i)
return bestC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maximalRectangle(vector<vector<char>> &matrix) {
int cols = int(matrix[0].size()), best = 0;
vector<int> heights(cols, 0);
for (auto &row : matrix) {
for (int c = 0; c < cols; c++)
heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
vector<int> stack;
for (int i = 0; i <= cols; i++) {
int h = (i == cols) ? 0 : heights[i];
while (!stack.empty() && heights[stack.back()] >= h) {
int height = heights[stack.back()];
stack.pop_back();
int left = stack.empty() ? -1 : stack.back();
best = max(best, height * (i - left - 1));
}
stack.push_back(i);
}
}
return best;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Basic Calculator (Hard)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Sliding Window Maximum (Hard)