Maximal Rectangle Problem
Description
LeetCode Problem 85.
Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
Explanation: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = []
Output: 0
Example 3:
Input: matrix = [["0"]]
Output: 0
Example 4:
Input: matrix = [["1"]]
Output: 1
Example 5:
Input: matrix = [["0","0"]]
Output: 0
Constraints:
- rows == matrix.length
- cols == matrix[i].length
- 0 <= row, cols <= 200
- matrix[i][j] is '0' or '1'.
Solution
Approach: Histogram per Row with a Monotonic Stack
Fix a row as the bottom edge of the rectangle. For each column, count how many consecutive '1's end at that row going up: this gives a histogram of bar heights, and the largest all-'1' rectangle with its bottom on this row is the largest rectangle in that histogram (problem 84). The answer is the best over all rows.
The heights are cheap to update from one row to the next:
heights[c] = heights[c] + 1if the cell is'1',heights[c] = 0if it is'0'(the column of ones is broken).
row 0: 1 0 1 0 0 heights 1 0 1 0 0
row 1: 1 0 1 1 1 heights 2 0 2 1 1
row 2: 1 1 1 1 1 heights 3 1 3 2 2 -> best rectangle 3 x 2 = 6
row 3: 1 0 0 1 0 heights 4 0 0 3 0
For each histogram, use a stack of column indices with increasing heights. When the bar at index i is not taller than the bar on top of the stack, pop the top: its rectangle ends at i - 1 and starts just after the new top (its nearest lower bar on the left), so its width is i - (top + 1). An imaginary bar of height 0 after the last column pops whatever is left.
Remember the empty matrix ([]): there is no first row to read the number of columns from, so return 0 right away.
Complexity: O(rows · cols) time, since each row's histogram is processed in O(cols), and O(cols) extra space for the heights and the stack.
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
cols = len(matrix[0])
heights = [0] * cols # heights[c]: consecutive '1's ending at the current row in column c
best = 0
for row in matrix:
for c in range(cols):
heights[c] = heights[c] + 1 if row[c] == "1" else 0
best = max(best, self.largest_in_histogram(heights))
return best
def largest_in_histogram(self, heights: List[int]) -> int:
n = len(heights)
stack = [] # indices of bars, heights increasing from bottom to top
best = 0
for i in range(n + 1):
# An imaginary bar of height 0 after the end pops every bar left on the stack.
current = heights[i] if i < n else 0
while stack and heights[stack[-1]] >= current:
height = heights[stack.pop()]
# This bar's rectangle spans from just after the new stack top up to i - 1.
left = stack[-1] + 1 if stack else 0
best = max(best, height * (i - left))
stack.append(i)
return best
Now write it from memory
Close the write-up and solve it yourself against the tests.