{x}
blog image

Maximal Rectangle

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 Explanation: Maximal Rectangle

This problem asks to find the largest rectangle containing only '1's in a given binary matrix. The most efficient approach uses a combination of a monotonic stack and dynamic programming-like thinking. The solution breaks down into two main parts:

1. Largest Rectangle in a Histogram:

This is a subproblem that needs to be solved repeatedly for each row of the input matrix. Imagine each row as a histogram where each bar's height represents the consecutive '1's in that column. The task is to find the largest rectangular area within this histogram. This is efficiently solved using a monotonic stack.

  • Monotonic Stack: A stack is used to maintain indices of the bars in increasing order of height.
  • Left and Right Boundaries: For each bar (column), the monotonic stack helps find the leftmost and rightmost indices where the bars are greater than or equal to the current bar's height. This defines the width of the rectangle with the current bar as its height.
  • Area Calculation: The area of the rectangle is then calculated as height[i] * (right[i] - left[i] - 1).

2. Iterating Through Rows:

The main algorithm iterates through each row of the input matrix. For each row:

  • Update Heights: It updates the heights array, which stores the heights of the histogram bars. If the current cell is '1', the height of the corresponding bar is incremented; otherwise, it's reset to 0.
  • Calculate Maximal Rectangle: The largestRectangleArea function (which uses the monotonic stack) is called to find the maximum area in the current row's histogram.
  • Update Maximum Area: The maximum area found so far is updated if a larger area is found in the current row.

Time Complexity Analysis:

  • largestRectangleArea function: The monotonic stack iterates through the heights array at most twice (once for left boundary, once for right boundary). Therefore, its time complexity is O(n), where n is the number of columns in the matrix.
  • Main algorithm: The main algorithm iterates through each row (m rows) and calls largestRectangleArea for each row. Thus, the overall time complexity is O(m * n).

Space Complexity Analysis:

The space complexity is dominated by the heights array (size n) and the monotonic stack (whose size, in the worst case, can be n). Therefore, the space complexity is O(n).

Code Explanations (Python example):

The Python code provided implements this solution effectively. Here's a breakdown:

class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        heights = [0] * len(matrix[0]) # Initialize heights array for histogram
        ans = 0 # Initialize max area
        for row in matrix: # Iterate through rows
            for j, v in enumerate(row): # Update heights for each column
                if v == "1":
                    heights[j] += 1
                else:
                    heights[j] = 0
            ans = max(ans, self.largestRectangleArea(heights)) # Find max area in current row
        return ans
 
    def largestRectangleArea(self, heights: List[int]) -> int:
        # ... (Monotonic stack implementation as shown in the provided code) ...

The largestRectangleArea function uses a monotonic stack to efficiently compute the maximum rectangular area within the histogram represented by heights. The main maximalRectangle function iterates through the rows, updating the heights array and finding the maximum area across all rows. The other language implementations follow a similar structure.