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.
For example:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
In this example, the largest rectangle containing only 1's has an area of 6.
Another example:
Input: matrix = [["0"]]
Output: 0
Here, since there are no 1's, the largest rectangle has an area of 0.
And a final example:
Input: matrix = [["1"]]
Output: 1
In this case, the largest rectangle is just a single 1, so the area is 1.
Could you provide an algorithm to solve this problem efficiently, considering the constraints that 1 <= rows, cols <= 200
and matrix[i][j]
is either '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:
The maximal rectangle problem asks for the biggest rectangular area we can find within a grid filled with ones and zeros. The brute force method involves checking every possible rectangle we can make and figuring out if it's valid.
Here's how the algorithm would work step-by-step:
def maximal_rectangle_brute_force(matrix):
if not matrix:
return 0
rows = len(matrix)
cols = len(matrix[0])
max_area = 0
for top_row in range(rows):
for left_col in range(cols):
# Iterate through all possible bottom-right corners for the chosen top-left
for bottom_row in range(top_row, rows):
for right_col in range(left_col, cols):
is_valid_rectangle = True
# Check if the submatrix contains only 1s
for row_to_check in range(top_row, bottom_row + 1):
for col_to_check in range(left_col, right_col + 1):
if matrix[row_to_check][col_to_check] == '0':
is_valid_rectangle = False
break
if not is_valid_rectangle:
break
# Calculate area only for valid rectangles
if is_valid_rectangle:
rectangle_width = right_col - left_col + 1
rectangle_height = bottom_row - top_row + 1
area = rectangle_width * rectangle_height
max_area = max(max_area, area)
return max_area
The best way to find the biggest rectangle in the grid is to think about building it up row by row. We treat each row as a series of bars and use information from the rows above to figure out how tall the bars can be, then we find the biggest rectangle using these bars.
Here's how the algorithm would work step-by-step:
def maximal_rectangle(matrix):
if not matrix:
return 0
number_of_rows = len(matrix)
number_of_columns = len(matrix[0])
heights = [[0] * number_of_columns for _ in range(number_of_rows)]
max_area = 0
for row_index in range(number_of_rows):
for column_index in range(number_of_columns):
if matrix[row_index][column_index] == '1':
# Accumulate heights based on consecutive '1's.
heights[row_index][column_index] = (heights[row_index - 1][column_index] + 1
if row_index > 0 else 1)
# Find the largest rectangle area for the current row.
max_area = max(max_area, largest_rectangle_area(heights[row_index]))
return max_area
def largest_rectangle_area(heights):
stack = []
max_area = 0
index = 0
while index < len(heights):
if not stack or heights[index] > heights[stack[-1]]:
stack.append(index)
index += 1
else:
# Calculate area when encountering a smaller height
top = stack.pop()
area = (heights[top] *
(index - stack[-1] - 1 if stack else index))
max_area = max(max_area, area)
# Process remaining bars in the stack
while stack:
top = stack.pop()
#Calculate area with the remaining histogram bars
area = (heights[top] *
(index - stack[-1] - 1 if stack else index))
max_area = max(max_area, area)
return max_area
Case | How to Handle |
---|---|
Null or empty matrix | Return 0 immediately as there's no rectangle to compute. |
Matrix with zero rows or columns | Return 0, as a rectangle requires at least one row and one column. |
Matrix with a single row | Treat the row as a histogram and calculate the largest rectangular area in it. |
Matrix with a single column | Calculate the maximum consecutive '1's multiplied by the width (which is 1). |
Matrix filled entirely with '0's | Return 0, as no rectangle of '1's can be formed. |
Matrix filled entirely with '1's | Return the area of the entire matrix (rows * cols). |
Integer overflow when calculating area (height * width) | Use long or equivalent data type to store the intermediate area result before comparison. |
Large matrix that might cause stack overflow if using recursive histogram area calculation | Implement the histogram area calculation iteratively using a stack to avoid stack overflow. |