Maximal Rectangle — LeetCode 85 Python Solution
HardStackArrayDynamic ProgrammingMatrixMonotonic Stack
- Problem
- #85
- Pattern
- Stack
- Reading time
- 6 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(m \times n), where m is the number of rows in matrix and n is the number of columns in matrix |
| Space | O(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
LeetCode 1504Count Submatrices With All OnesMediumLeetCode 2617Minimum Number of Visited Cells in a GridHardLeetCode 907Sum of Subarray MinimumsMediumLeetCode 975Odd Even JumpHardLeetCode 1130Minimum Cost Tree From Leaf ValuesMediumLeetCode 1526Minimum Number of Increments on Subarrays to Form a Target ArrayHard
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.