Maximal Rectangle
Hard
Topics
Given a rows-of-characters binary matrix grid filled with '0' and '1', find the largest rectangle containing only '1's and return its area.
Example 1
1 rectangle, area 6. Unlike the square version the sides can differ, which is why the usual trick is to read each row as a histogram of the 1-runs above it.Input: matrix = ["10100","10111","11111","10010"] Output: 6
Example 2
Input: matrix = ["0"] Output: 0
Example 3
Input: matrix = ["1"] Output: 1
Constraints
- 1 <= rows, cols <= 200
- grid[i][j] is '0' or '1'.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The brute force picks every pair of corners, which is O((rows*cols)^2) rectangles, and verifies each is all ones in O(rows*cols). That is O(n^6) on a square grid — a useful thing to say and then abandon.
The better framing comes from asking what a maximal rectangle actually is. Every rectangle of ones has a bottom edge, sitting on some row. So instead of searching rectangles, fix the bottom row and ask for the best rectangle whose bottom edge lies there. Do that for each of the rows rows and take the maximum; no rectangle is missed, because every rectangle has exactly one bottom row.
Once the bottom row is fixed, the grid above it collapses into a single array. For each column, count how many consecutive ones run upward from that row. That is a histogram, and the question "largest rectangle of ones with its bottom edge on this row" becomes exactly "largest rectangle in this histogram" — a known problem with a linear solution.
💡 Largest rectangle in a histogram: for each bar, the widest rectangle of that bar's height extends left and right until it meets a shorter bar. A monotonic increasing stack finds both boundaries in one pass, because a bar is popped precisely when the first shorter bar to its right appears, and whatever sits below it on the stack is the first shorter bar to its left.
The histogram also updates incrementally. Moving from one row to the next, a column with a 1 extends its run by one and a column with a 0 resets to zero, so each row costs O(cols) rather than a fresh upward count.
Approach
- Keep a
heightsarray of lengthcols, all zeros. - For each row, update every column:
heights[c] += 1on a'1', orheights[c] = 0on a'0'. The reset is what encodes the rectangle being blocked. - Run the monotonic-stack histogram scan over
heightsand fold the result into the running best. - Use a sentinel height of 0 one past the end, so the final pass drains the stack and the last bars get measured with no separate cleanup loop.
- Return the best over all rows.
Width on pop is i - stack.top() - 1 when the stack is non-empty, and i when it is empty — the empty case meaning this bar is the shortest seen so far, so it reaches all the way back to column 0.
Dry Run
The standard grid, answer 6.
row 0: 1 0 1 0 0 heights = [1,0,1,0,0] best in row = 1 best = 1
row 1: 1 0 1 1 1 heights = [2,0,2,1,1] best in row = 3 best = 3
row 2: 1 1 1 1 1 heights = [3,1,3,2,2] best in row = 6 best = 6
row 3: 1 0 0 1 0 heights = [4,0,0,3,0] best in row = 4 best = 6
answer 6Row 2 is where the answer appears: heights [3,1,3,2,2] contain a rectangle of height 2 spanning the last three columns and reaching back to column 2 — width 3, height 2, area 6. Two details worth noticing. Row 3 has the tallest single bar in the whole run (height 4) and yet a worse area, which is why the maximum has to be taken over every row rather than the row with the tallest column. And the 0 at column 1 in row 0 keeps resetting, so that column never contributes height until row 2.
Complexity
- Time — O(rows * cols): each row costs O(cols) to update the histogram plus O(cols) for the stack scan, since every column index is pushed once and popped once per row. With
rows, cols <= 200that is about 40,000 steps. Against O((rows*cols)^2) for enumerating corner pairs. - Space — O(cols): the
heightsarray and the stack, both bounded by the column count. Note it does not need the grid copied or a second 2-D table — a common first implementation builds anrows x colstable of upward runs, which works but is O(rows*cols) space for no benefit, since only the current row's histogram is ever read.
Common Pitfalls
- Adding to a column's height instead of resetting it on a
'0'. The reset is the only thing that stops a rectangle passing through a blocked cell. - Computing width as
i - toprather thani - stack.top() - 1, or forgetting that an empty stack means widthi. These off-by-ones give answers that are right on symmetric examples and wrong on real ones. - Omitting the trailing sentinel and leaving bars on the stack unmeasured. A fully increasing histogram such as
[1,2,3]then reports 0. - Using strict
>instead of>=when popping. With equal heights the popped bar's width is understated;>=works because the last of a run of equal bars measures the full span. - Comparing
'1'against the integer1. The grid holds characters here, and the mismatch silently makes every cell a zero. - Resetting the stack but not the heights between rows, or vice versa. The stack is per-row scratch; the heights deliberately carry over.
Full Solution — all languages
class Solution:
def maximalRectangle(self, grid):
if not grid or not grid[0]:
return 0
C = len(grid[0])
heights = [0] * C
best = 0
for row in grid:
for c in range(C):
heights[c] = heights[c] + 1 if row[c] == '1' else 0
stack = []
for i in range(C + 1):
h = 0 if i == C else heights[i]
while stack and heights[stack[-1]] >= h:
top = stack.pop()
width = i - stack[-1] - 1 if stack else i
best = max(best, heights[top] * width)
stack.append(i)
return bestimport java.util.*;
class Solution {
public int maximalRectangle(char[][] grid) {
if (grid.length == 0 || grid[0].length == 0) return 0;
int C = grid[0].length;
int[] heights = new int[C];
int best = 0;
for (char[] row : grid) {
for (int c = 0; c < C; c++) heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= C; i++) {
int h = i == C ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peek()] >= h) {
int top = stack.pop();
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
best = Math.max(best, heights[top] * width);
}
stack.push(i);
}
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maximalRectangle(vector<vector<char>>& grid) {
if (grid.empty() || grid[0].empty()) return 0;
int C = grid[0].size();
vector<int> heights(C, 0);
int best = 0;
for (auto& row : grid) {
for (int c = 0; c < C; c++) heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
vector<int> stack;
for (int i = 0; i <= C; i++) {
int h = i == C ? 0 : heights[i];
while (!stack.empty() && heights[stack.back()] >= h) {
int top = stack.back();
stack.pop_back();
int width = stack.empty() ? i : i - stack.back() - 1;
best = max(best, heights[top] * width);
}
stack.push_back(i);
}
}
return best;
}
};/**
* @param {character[][]} grid
* @return {number}
*/ var maximalRectangle = function(grid) {
if (!grid.length || !grid[0].length) return 0;
const C = grid[0].length;
const heights = new Array(C).fill(0);
let best = 0;
for (const row of grid) {
for (let c = 0; c < C; c++) heights[c] = row[c] === '1' ? heights[c] + 1 : 0;
const stack = [];
for (let i = 0; i <= C; i++) {
const h = i === C ? 0 : heights[i];
while (stack.length && heights[stack[stack.length - 1]] >= h) {
const top = stack.pop();
const width = stack.length ? i - stack[stack.length - 1] - 1 : i;
best = Math.max(best, heights[top] * width);
}
stack.push(i);
}
}
return best;
};