#85

Maximal Rectangle

Hard
ArrayDynamic ProgrammingStackMatrixMonotonic StackHistogram AreaDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m)
Space
O(1)
O(m)
💡

Intuition

Time O(n * m)Space O(m)

The optimal solution transforms the problem into a series of histogram problems. By treating each row as the base of a histogram, we can efficiently calculate the largest rectangle using a stack.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create an array to store heights of 1's for each column.
  2. 2Step 2: For each row in the matrix, update the heights array. If the cell is '1', increment the height; if it's '0', reset the height to 0.
  3. 3Step 3: For each updated heights array, calculate the maximum rectangle area using a stack to find the largest rectangle in the histogram.
solution.py22 lines
1def maximalRectangle(matrix):
2    if not matrix:
3        return 0
4    max_area = 0
5    heights = [0] * len(matrix[0])
6    for row in matrix:
7        for i in range(len(row)):
8            heights[i] = heights[i] + 1 if row[i] == '1' else 0
9        max_area = max(max_area, largestRectangleArea(heights))
10    return max_area
11
12def largestRectangleArea(heights):
13    heights.append(0)
14    stack = []
15    max_area = 0
16    for i in range(len(heights)):
17        while stack and heights[stack[-1]] > heights[i]:
18            h = heights[stack.pop()]
19            w = i if not stack else i - stack[-1] - 1
20            max_area = max(max_area, h * w)
21        stack.append(i)
22    return max_area

Complexity note: The time complexity is O(n * m) because we iterate through each cell in the matrix once and then process the heights array, while the space complexity is O(m) for the heights array.

  • 1Transforming the problem into histograms allows for efficient area calculations.
  • 2Using a stack helps manage heights and widths effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.