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 = [["0"]] Output: 0
Example 3:
Input: matrix = [["1"]] Output: 1
Constraints:
rows == matrix.lengthcols == matrix[i].length1 <= row, cols <= 200matrix[i][j] is '0' or '1'.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine looking at a grid made of zeroes and ones and trying to find the biggest possible solid block made entirely of ones. The brute force approach is like checking every possible rectangular shape you can draw on the grid and seeing which one is the largest.
Here's how the algorithm would work step-by-step:
def maximal_rectangle(matrix):
if not matrix or not matrix[0]:
return 0
row_count = len(matrix)
col_count = len(matrix[0])
max_area_found = 0
# Iterate through every possible starting cell to evaluate all rectangle permutations
for start_row in range(row_count):
for start_col in range(col_count):
# Expand dimensions outward to test every unique width and height configuration
for current_height in range(start_row, row_count):
for current_width in range(start_col, col_count):
contains_only_ones = True
for check_row in range(start_row, current_height + 1):
for check_col in range(start_col, current_width + 1):
if matrix[check_row][check_col] == '0':
contains_only_ones = False
# Calculate the area only if the shape is entirely valid to find the max
if contains_only_ones:
rectangle_width = (current_width - start_col) + 1
rectangle_height = (current_height - start_row) + 1
current_area = rectangle_width * rectangle_height
if current_area > max_area_found:
max_area_found = current_area
# Return the largest valid rectangle area discovered across all brute force checks
return max_area_foundInstead of checking every possible rectangle in the grid one by one, the optimal approach breaks the problem down by looking at each row as the ground floor of a skyline. By calculating the maximum rectangular area formed by these vertical heights row by row, we can efficiently find the biggest rectangle overall.
Here's how the algorithm would work step-by-step:
class Solution:
def maximalRectangle(self, matrix: list[list[str]]) -> int:
if not matrix or not matrix[0]:
return 0
max_area_found = 0
number_of_cols = len(matrix[0])
pillar_heights = [0] * number_of_cols
for row_values in matrix:
for col_index in range(number_of_cols):
if row_values[col_index] == '1':
pillar_heights[col_index] += 1
else:
pillar_heights[col_index] = 0
# We use a monotonic stack to efficiently find the largest rectangle for the current row's skyline.
stack_indices = []
for current_index in range(number_of_cols + 1):
current_height = pillar_heights[current_index] if current_index < number_of_cols else 0
while stack_indices and current_height < pillar_heights[stack_indices[-1]]:
popped_height_index = stack_indices.pop()
height_value = pillar_heights[popped_height_index]
width_span = current_index if not stack_indices else current_index - stack_indices[-1] - 1
max_area_found = max(max_area_found, height_value * width_span)
stack_indices.append(current_index)
# We return the absolute maximum rectangular area discovered across all processed row skylines.
return max_area_found| Case | How to Handle |
|---|---|
| Empty matrix or null input where rows or columns equal zero | Return zero immediately because no rectangle can be formed. |
| Matrix containing only zeros | Histogram heights remain zero throughout, resulting in a maximum area of zero. |
| Matrix containing only ones | Cumulative heights accumulate correctly row by row, and the largest rectangle area will equal the total number of cells in the grid. |
| Single row or single column matrix | The algorithm treats the single dimension as a one-dimensional array and correctly calculates the maximum consecutive ones. |
| Highly skewed matrices such as extremely tall and thin or extremely short and wide | The histogram and stack approach processes each row and column in linear time ensuring optimal efficiency. |
| Disconnected islands of ones scattered across the matrix | The stack correctly computes maximum rectangular areas for independent histogram peaks without cross-contamination. |
| Maximum constraints on rows and columns up to the upper limits | Using O(cols) space and O(rows * cols) time prevents memory limit exceed and time limit exceed errors. |
| Alternating rows of zeros and ones creating complex boundary transitions | Resetting the histogram height to zero when encountering a zero ensures boundaries are strictly respected. |