85. Maximal Rectangle
Asked at 15Google51Amazon47Microsoft43Bloomberg42Meta41WorldQuant83Zeta64Sprinklr54Intuit43Zoho42Visa39DE Shaw38Goldman Sachs36tcs36Salesforce35
Problem
Given a binary matrix of '0'/'1' characters, return the area of the largest rectangle containing only '1's.
Example: ["10100","10111","11111","10010"] → 6
Constraints: up to 200 × 200.
Treat each row as the floor of a histogram: h[c] = consecutive 1s ending at this row. Run Largest Rectangle in Histogram on every row.
row 0 1 0 1 0 0 h = 1 0 1 0 0
row 1 1 0 1 1 1 h = 2 0 2 1 1
row 2 1 1 1 1 1 h = 3 1 3 2 2 -> histogram max 6
Complexity: O(rows × cols).
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
h = [0] * len(matrix[0])
best = 0
for row in matrix:
for c, v in enumerate(row):
h[c] = h[c] + 1 if v == "1" else 0
st = []
for i, x in enumerate(h + [0]):
while st and h[st[-1]] >= x:
top = h[st.pop()]
best = max(best, top * (i - (st[-1] if st else -1) - 1))
st.append(i)
return best
M = ["10100", "10111", "11111", "10010"]
assert Solution().maximalRectangle([list(r) for r in M]) == 6
assert Solution().maximalRectangle([["0"]]) == 0
assert Solution().maximalRectangle([["1"]]) == 1
assert Solution().maximalRectangle([list(r) for r in ["0110", "1111", "1110"]]) == 6
class Solution {
public int maximalRectangle(char[][] matrix) {
int cols = matrix[0].length, best = 0;
int[] h = new int[cols];
for (char[] row : matrix) {
for (int c = 0; c < cols; c++) h[c] = row[c] == '1' ? h[c] + 1 : 0;
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i <= cols; i++) {
int x = i == cols ? 0 : h[i];
while (!st.isEmpty() && h[st.peek()] >= x) {
int top = h[st.pop()];
best = Math.max(best, top * (i - (st.isEmpty() ? -1 : st.peek()) - 1));
}
st.push(i);
}
}
return best;
}
}
func maximalRectangle(matrix [][]byte) int {
if len(matrix) == 0 {
return 0
}
h := make([]int, len(matrix[0])) // histogram of 1s ending at this row
best := 0
for _, row := range matrix {
for c, v := range row {
if v == '1' {
h[c]++
} else {
h[c] = 0
}
}
st := []int{}
for i := 0; i <= len(h); i++ {
x := 0
if i < len(h) {
x = h[i]
}
for len(st) > 0 && h[st[len(st)-1]] >= x {
top := h[st[len(st)-1]]
st = st[:len(st)-1]
left := -1
if len(st) > 0 {
left = st[len(st)-1]
}
best = max(best, top*(i-left-1))
}
st = append(st, i)
}
}
return best
}