85. Maximal Rectangle
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the area of the largest rectangle composed entirely of '1's within a 2D binary matrix. A brute-force approach of checking every possible rectangle would be too slow. The core challenge is to find an efficient way to calculate the areas of all-one rectangles.
Solution
Maximal Rectangle in Python
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
heights = [0] * cols
max_area = 0
for i in range(rows):
# Update heights for the current row
for j in range(cols):
if matrix[i][j] == '1':
heights[j] += 1
else:
heights[j] = 0
# Calculate the largest rectangle for the histogram based on the current row
max_area = max(max_area, self.largestRectangleArea(heights))
return max_area
def largestRectangleArea(self, heights: List[int]) -> int:
# Helper function to solve Largest Rectangle in Histogram (LeetCode 84)
# Add a sentinel bar of height 0 to handle remaining bars in the stack
stack = [-1] # Sentinel for calculation of width
max_area = 0
for i, h in enumerate(heights):
while stack[-1] != -1 and heights[stack[-1]] >= h:
height = heights[stack.pop()]
width = i - stack[-1] - 1
max_area = max(max_area, height * width)
stack.append(i)
# After iterating through all bars, process remaining bars in the stack
while stack[-1] != -1:
height = heights[stack.pop()]
width = len(heights) - stack[-1] - 1
max_area = max(max_area, height * width)
return max_area
Maximal Rectangle in Java
class Solution {
public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int rows = matrix.length;
int cols = matrix[0].length;
int[] heights = new int[cols];
int maxArea = 0;
for (int i = 0; i < rows; i++) {
// Update heights for the current row
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
// Calculate the largest rectangle for the histogram based on the current row
maxArea = Math.max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
// Helper function to solve Largest Rectangle in Histogram (LeetCode 84)
private int largestRectangleArea(int[] heights) {
Stack<Integer> stack = new Stack<>();
int maxArea = 0;
int[] h = new int[heights.length + 1];
System.arraycopy(heights, 0, h, 0, heights.length);
// h[heights.length] is 0, a sentinel value to pop all remaining bars
for (int i = 0; i < h.length; i++) {
while (!stack.isEmpty() && h[stack.peek()] >= h[i]) {
int height = h[stack.pop()];
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i);
}
return maxArea;
}
}
Maximal Rectangle in C++
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty() || matrix[0].empty()) {
return 0;
}
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> heights(cols, 0);
int maxArea = 0;
for (int i = 0; i < rows; ++i) {
// Update heights for the current row
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] == '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
// Calculate the largest rectangle for the histogram based on the current row
maxArea = max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
private:
// Helper function to solve Largest Rectangle in Histogram (LeetCode 84)
int largestRectangleArea(vector<int>& heights) {
stack<int> s;
int max_area = 0;
vector<int> h = heights;
h.push_back(0); // Sentinel value to ensure all bars are processed
for (int i = 0; i < h.size(); ++i) {
while (!s.empty() && h[s.top()] >= h[i]) {
int height = h[s.top()];
s.pop();
int width = s.empty() ? i : i - s.top() - 1;
max_area = max(max_area, height * width);
}
s.push(i);
}
return max_area;
}
};
Maximal Rectangle in TypeScript
function maximalRectangle(matrix: string[][]): number {
if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
return 0;
}
const rows = matrix.length;
const cols = matrix[0].length;
const heights: number[] = new Array(cols).fill(0);
let maxArea = 0;
const largestRectangleArea = (h: number[]): number => {
// Helper function to solve Largest Rectangle in Histogram (LeetCode 84)
const stack: number[] = [-1]; // Sentinel for width calculation
let max_area = 0;
for (let i = 0; i < h.length; i++) {
while (stack[stack.length - 1] !== -1 && h[stack[stack.length - 1]] >= h[i]) {
const height = h[stack.pop()!];
const width = i - stack[stack.length - 1] - 1;
max_area = Math.max(max_area, height * width);
}
stack.push(i);
}
while (stack[stack.length - 1] !== -1) {
const height = h[stack.pop()!];
const width = h.length - stack[stack.length - 1] - 1;
max_area = Math.max(max_area, height * width);
}
return max_area;
};
for (let i = 0; i < rows; i++) {
// Update heights for the current row
for (let j = 0; j < cols; j++) {
if (matrix[i][j] === '1') {
heights[j]++;
} else {
heights[j] = 0;
}
}
// Calculate the largest rectangle for the histogram based on the current row
maxArea = Math.max(maxArea, largestRectangleArea(heights));
}
return maxArea;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.