Maximal Rectangle — LeetCode 85 Python Solution

HardStackArrayDynamic ProgrammingMatrixMonotonic Stack
Problem
#85
Pattern
Stack
Reading time
6 min

The problem

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

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.

Python solution

Python
class Solution:
    def maximalRectangle(self, matrix: List[List[str]]) -> int:
        heights = [0] * len(matrix[0])
        ans = 0
        for row in matrix:
            for j, v in enumerate(row):
                if v == "1":
                    heights[j] += 1
                else:
                    heights[j] = 0
            ans = max(ans, self.largestRectangleArea(heights))
        return ans

    def largestRectangleArea(self, heights: List[int]) -> int:
        n = len(heights)
        stk = []
        left = [-1] * n
        right = [n] * n
        for i, h in enumerate(heights):
            while stk and heights[stk[-1]] >= h:
                stk.pop()
            if stk:
                left[i] = stk[-1]
            stk.append(i)
        stk = []
        for i in range(n - 1, -1, -1):
            h = heights[i]
            while stk and heights[stk[-1]] >= h:
                stk.pop()
            if stk:
                right[i] = stk[-1]
            stk.append(i)
        return max(h * (right[i] - left[i] - 1) for i, h in enumerate(heights))

Complexity

MeasureComplexity
TimeO(m \times n), where m is the number of rows in matrix and n is the number of columns in matrix
SpaceO(n·m) or optimized auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 85. Maximal Rectangle is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 85. Maximal Rectangle?
LeetCode 85. Maximal Rectangle is rated Hard on LeetCode.
What topics does LeetCode 85. Maximal Rectangle cover?
LeetCode 85. Maximal Rectangle is tagged Stack, Array, Dynamic Programming, Matrix and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview