Taro Logo

Maximal Rectangle

#39 Most AskedHard
1 view
Topics:
ArraysDynamic ProgrammingStacks

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.length
  • cols == matrix[i].length
  • 1 <= row, cols <= 200
  • matrix[i][j] is '0' or '1'.

Solution


Clarifying Questions

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:

  1. What should we return if the input matrix is empty or null?
  2. Are the characters in the matrix strictly guaranteed to be only '0' and '1', or could there be other unexpected characters?
  3. Can the dimensions of the grid (`rows` and `cols`) be vastly different, such as a very long single row or a single column?
  4. If there are multiple rectangles with the exact same maximal area, does it matter which one's area we return?
  5. Should we modify the input matrix in place, or is it expected that we keep it read-only?

Brute Force Solution

Approach

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:

  1. Start at the top-left corner of the grid and pick a starting point.
  2. From that starting point, try every possible width and height to draw a rectangle of every conceivable size.
  3. Look inside each drawn rectangle to make sure it contains only ones and does not accidentally include any zeroes.
  4. If a rectangle contains even a single zero, ignore it and move on to the next one.
  5. If the rectangle contains only ones, measure its total area by multiplying its width by its height.
  6. Keep track of the largest area you have found so far.
  7. Repeat this process by trying every other possible starting point on the grid until you have checked every single potential rectangle.
  8. At the very end, report the largest area you discovered across all your checks.

Code Implementation

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_found

Big(O) Analysis

Time Complexity
O(R^3 * C^3) – Let R be the number of rows and C be the number of columns in the grid, making the total input size driven by these dimensions. For every possible starting cell in the grid, we iterate through every possible width and height combination to draw every conceivable rectangle. Inside each drawn rectangle, we inspect all of its cells to ensure it contains only ones. This requires nested loops over starting coordinates, widths, heights, and the cells within the shape, leading to a polynomial cost of approximately (R * C)^3 operations. Simplifying this massive nested iteration results in a final Big O time complexity of O(R^3 * C^3).
Space Complexity
O(n) – To find the maximal rectangle, the algorithm maintains row-by-row heights and uses a stack to compute the largest rectangular area in a histogram. The auxiliary data structures consist of a height array and a stack, both scaling with the number of columns in the grid. If we define N as the total number of cells in the grid with dimensions R rows and C columns, the space used by the height array and stack is proportional to C. In the worst case where C is proportional to N, the extra memory required scales linearly with the input size. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

Instead 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:

  1. Begin by looking at the very first row of the grid and treat it as a skyline made of vertical pillars whose heights match the consecutive blocks of solid ground.
  2. Calculate the largest possible rectangular area that can fit under this first skyline by finding the widest possible span for each pillar's height.
  3. Move down to the next row and update your skyline: wherever there is solid ground, make the pillar taller, but wherever there is a gap, reset the pillar's height completely back to zero.
  4. Repeat the process of calculating the largest possible rectangular area for this new, updated skyline.
  5. Continue this process row by row until you reach the bottom of the grid, updating the overall record whenever you find a rectangle larger than your previous best.
  6. By reusing the work from the previous rows instead of starting from scratch every time, you quickly arrive at the largest possible rectangle without wasting effort.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(R * C) – Let R be the number of rows and C be the number of columns in the grid, which represent our input size. For every single row in the grid, we iterate through all C columns to update the skyline heights and to calculate the largest rectangle using a monotonic stack. Since the linear stack operation takes time proportional to the number of columns, processing each row requires proportional effort. This outer loop over R rows combined with the inner column processing leads to approximately R * C operations, which simplifies to O(R * C).
Space Complexity
O(M) – To calculate the maximum rectangular area for each row skyline, we maintain an auxiliary integer array or stack of size M, where M represents the number of columns in the grid. Additionally, a few primitive variables store the running heights and maximum area, which require constant extra space. As we iterate through the rows, this same row-sized structure is reused, meaning the peak auxiliary memory does not scale with the number of rows. Therefore, defining N as the total number of elements in the grid (N = R times M), the auxiliary space complexity simplifies to O(M) or O(square root of N) in the worst-case scenario where dimensions are equal.

Edge Cases

Empty matrix or null input where rows or columns equal zero
How to Handle:
Return zero immediately because no rectangle can be formed.
Matrix containing only zeros
How to Handle:
Histogram heights remain zero throughout, resulting in a maximum area of zero.
Matrix containing only ones
How to Handle:
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
How to Handle:
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
How to Handle:
The histogram and stack approach processes each row and column in linear time ensuring optimal efficiency.
Disconnected islands of ones scattered across the matrix
How to Handle:
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
How to Handle:
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
How to Handle:
Resetting the histogram height to zero when encountering a zero ensures boundaries are strictly respected.
0/45 completed