Maximal Rectangle

Pattern: Monotonic stack

hard

Treat each row as the ground of a histogram: a column's height is how many 1s stand in a row above it, ending at this row. The largest rectangle of 1s is the best Largest Rectangle in Histogram over all rows.

The problem

Given a grid of '0' and '1' characters, return the area of the largest rectangle containing only '1'. The grid 10100 / 10111 / 11111 / 10010 gives 6.

Think first

  • Fix the bottom row of the rectangle. What does the area above look like?
  • How do the heights change from one row to the next?
  • Which problem finds the largest rectangle in a histogram?

Hints

    Brute force, and why it fails

    Try every pair of top and bottom rows and scan the columns: O(rows² × cols).

    The key insight

    Every rectangle has a bottom row, and above that row the grid of 1s is a histogram. So one histogram problem per row solves the whole grid.

    Dry run

    10 
    01 
    12 
    03 
    04 
    best1

    Row 0 "10100": heights [1, 0, 1, 0, 0]. Best area 1.

    Step 1 of 4

    The plan

    heights = [0] * cols
    for each row:
        heights[c] = heights[c] + 1 if row[c] == '1' else 0
        best = max(best, largestRectangle(heights))
    

    Complexity

    Time
    O(rows × cols)
    Space
    O(cols)

    Each row updates the heights and runs an O(cols) histogram pass.

    Edge cases

    • A single cell.
    • All zeros: 0.
    • A full grid: rows × cols.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int maximalRectangle(char[][] matrix) {
            int cols = matrix[0].length, best = 0;
            int[] heights = new int[cols];                  // for each column, the run of 1s ending at this row
            for (char[] row : matrix) {
                for (int c = 0; c < cols; c++) heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
                best = Math.max(best, largest(heights));    // the best rectangle whose bottom is this row
            }
            return best;
        }
    
        private int largest(int[] heights) {                // Largest Rectangle in Histogram
            int n = heights.length, best = 0;
            Deque<Integer> st = new ArrayDeque<>();
            for (int i = 0; i <= n; i++) {
                int h = i == n ? 0 : heights[i];
                while (!st.isEmpty() && heights[st.peek()] >= h) {
                    int height = heights[st.pop()];
                    int left = st.isEmpty() ? -1 : st.peek();
                    best = Math.max(best, height * (i - left - 1));
                }
                st.push(i);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int maximalRectangle(vector<vector<char>>& matrix) {
            int cols = static_cast<int>(matrix[0].size()), best = 0;
            vector<int> heights(cols, 0);                   // for each column, the run of 1s ending at this row
            for (const vector<char>& row : matrix) {
                for (int c = 0; c < cols; c++) heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
                best = max(best, largest(heights));         // the best rectangle whose bottom is this row
            }
            return best;
        }
    
        int largest(vector<int>& heights) {                 // Largest Rectangle in Histogram
            int n = static_cast<int>(heights.size()), best = 0;
            stack<int> st;
            for (int i = 0; i <= n; i++) {
                int h = i == n ? 0 : heights[i];
                while (!st.empty() && heights[st.top()] >= h) {
                    int height = heights[st.top()];
                    st.pop();
                    int left = st.empty() ? -1 : st.top();
                    best = max(best, height * (i - left - 1));
                }
                st.push(i);
            }
            return best;
        }
    };

    Python

    class Solution:
        def maximalRectangle(self, matrix: list[list[str]]) -> int:
            heights = [0] * len(matrix[0])          # for each column, the run of 1s ending at this row
            best = 0
            for row in matrix:
                heights = [h + 1 if ch == "1" else 0 for h, ch in zip(heights, row)]
                best = max(best, self.largest(heights))   # the best rectangle whose bottom is this row
            return best
    
        def largest(self, heights: list[int]) -> int:   # Largest Rectangle in Histogram
            n, best, st = len(heights), 0, []
            for i in range(n + 1):
                h = 0 if i == n else heights[i]
                while st and heights[st[-1]] >= h:
                    height = heights[st.pop()]
                    left = st[-1] if st else -1
                    best = max(best, height * (i - left - 1))
                st.append(i)
            return best

    Common mistakes

    • Resetting all heights each row instead of carrying them.
    • Treating the characters '1' as the number 1.

    Similar problems