Coding Interview PatternsMaximal Rectangle
HardMonotonic Stack
Maximal Rectangle
Explanation & Solution
Description
Given a 2D binary matrix filled with '0's and '1's, find the largest rectangle containing only 1's and return its area.
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 of all 1's has an area of 6, formed by the submatrix spanning rows 1-2 and columns 2-4.
Constraints
rows == matrix.lengthcols == matrix[i].length1 <= rows, cols <= 200matrix[i][j]is'0'or'1'
Approach
Monotonic Stack pattern
1. Build a Histogram Row by Row
- Maintain a
heightsarray of lengthcols, initialized to all zeros - For each row in the matrix, update each column's height: if
matrix[r][c]is'1', incrementheights[c]by 1; otherwise reset it to 0 - This transforms the 2D problem into a series of "largest rectangle in histogram" problems
2. Apply Largest Rectangle in Histogram
- After updating
heightsfor each row, compute the largest rectangle area in the current histogram - Use a monotonic stack to efficiently find the largest rectangle
3. Monotonic Stack Approach
- Iterate through the histogram bars from left to right
- Maintain a stack of indices in increasing order of bar heights
- When the current bar is shorter than the bar at the top of the stack, pop from the stack
- For each popped bar, calculate the rectangle area using that bar's height and the width determined by the current index and the new stack top
4. Calculate Width for Each Popped Bar
- When popping index
jat current indexi, the width extends from the element after the new stack top toi - 1 - If the stack is empty after popping, the width is
i(the bar extends all the way to the left) - Otherwise, the width is
i - stack[top] - 1
5. Handle Remaining Bars
- After processing all bars, append a virtual bar of height 0 to flush all remaining bars from the stack
- This ensures every bar is processed and its maximum rectangle is considered
6. Track the Global Maximum
- After each row's histogram is processed, update the global
maxAreawith the largest rectangle found - Return
maxAreaafter all rows are processed
Key Insight
By building histograms row by row, we reduce the 2D maximal rectangle problem to repeated 1D largest-rectangle-in-histogram problems. The monotonic stack solves each histogram in O(cols) time, giving an overall time complexity of O(rows × cols). Space complexity is O(cols) for the heights array and the stack.
Visualization
Input:
DFS Traversal4×5 grid
output—
Press play to start dfs traversal
CurrentQueuedVisitedSource
81 steps