Maximal Rectangle

Hard

Topics
ArrayDynamic ProgrammingStackMatrix

Given a rows-of-characters binary matrix grid filled with '0' and '1', find the largest rectangle containing only '1's and return its area.

Example 1

01010011011121111131001001234
The shaded block is the largest all-1 rectangle, area 6. Unlike the square version the sides can differ, which is why the usual trick is to read each row as a histogram of the 1-runs above it.
Character grid — one row per line.
Input:  matrix = ["10100","10111","11111","10010"]
Output: 6

Example 2

000
Input:  matrix = ["0"]
Output: 0

Example 3

010
Input:  matrix = ["1"]
Output: 1

Constraints

  • 1 <= rows, cols <= 200
  • grid[i][j] is '0' or '1'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The brute force picks every pair of corners, which is O((rows*cols)^2) rectangles, and verifies each is all ones in O(rows*cols). That is O(n^6) on a square grid — a useful thing to say and then abandon.

The better framing comes from asking what a maximal rectangle actually is. Every rectangle of ones has a bottom edge, sitting on some row. So instead of searching rectangles, fix the bottom row and ask for the best rectangle whose bottom edge lies there. Do that for each of the rows rows and take the maximum; no rectangle is missed, because every rectangle has exactly one bottom row.

Once the bottom row is fixed, the grid above it collapses into a single array. For each column, count how many consecutive ones run upward from that row. That is a histogram, and the question "largest rectangle of ones with its bottom edge on this row" becomes exactly "largest rectangle in this histogram" — a known problem with a linear solution.

💡 Largest rectangle in a histogram: for each bar, the widest rectangle of that bar's height extends left and right until it meets a shorter bar. A monotonic increasing stack finds both boundaries in one pass, because a bar is popped precisely when the first shorter bar to its right appears, and whatever sits below it on the stack is the first shorter bar to its left.

The histogram also updates incrementally. Moving from one row to the next, a column with a 1 extends its run by one and a column with a 0 resets to zero, so each row costs O(cols) rather than a fresh upward count.

Approach

  1. Keep a heights array of length cols, all zeros.
  2. For each row, update every column: heights[c] += 1 on a '1', or heights[c] = 0 on a '0'. The reset is what encodes the rectangle being blocked.
  3. Run the monotonic-stack histogram scan over heights and fold the result into the running best.
  4. Use a sentinel height of 0 one past the end, so the final pass drains the stack and the last bars get measured with no separate cleanup loop.
  5. Return the best over all rows.

Width on pop is i - stack.top() - 1 when the stack is non-empty, and i when it is empty — the empty case meaning this bar is the shortest seen so far, so it reaches all the way back to column 0.

Dry Run

The standard grid, answer 6.

row 0:  1 0 1 0 0    heights = [1,0,1,0,0]   best in row = 1   best = 1
row 1:  1 0 1 1 1    heights = [2,0,2,1,1]   best in row = 3   best = 3
row 2:  1 1 1 1 1    heights = [3,1,3,2,2]   best in row = 6   best = 6
row 3:  1 0 0 1 0    heights = [4,0,0,3,0]   best in row = 4   best = 6

answer 6

Row 2 is where the answer appears: heights [3,1,3,2,2] contain a rectangle of height 2 spanning the last three columns and reaching back to column 2 — width 3, height 2, area 6. Two details worth noticing. Row 3 has the tallest single bar in the whole run (height 4) and yet a worse area, which is why the maximum has to be taken over every row rather than the row with the tallest column. And the 0 at column 1 in row 0 keeps resetting, so that column never contributes height until row 2.

Complexity

  • Time — O(rows * cols): each row costs O(cols) to update the histogram plus O(cols) for the stack scan, since every column index is pushed once and popped once per row. With rows, cols <= 200 that is about 40,000 steps. Against O((rows*cols)^2) for enumerating corner pairs.
  • Space — O(cols): the heights array and the stack, both bounded by the column count. Note it does not need the grid copied or a second 2-D table — a common first implementation builds an rows x cols table of upward runs, which works but is O(rows*cols) space for no benefit, since only the current row's histogram is ever read.

Common Pitfalls

  • Adding to a column's height instead of resetting it on a '0'. The reset is the only thing that stops a rectangle passing through a blocked cell.
  • Computing width as i - top rather than i - stack.top() - 1, or forgetting that an empty stack means width i. These off-by-ones give answers that are right on symmetric examples and wrong on real ones.
  • Omitting the trailing sentinel and leaving bars on the stack unmeasured. A fully increasing histogram such as [1,2,3] then reports 0.
  • Using strict > instead of >= when popping. With equal heights the popped bar's width is understated; >= works because the last of a run of equal bars measures the full span.
  • Comparing '1' against the integer 1. The grid holds characters here, and the mismatch silently makes every cell a zero.
  • Resetting the stack but not the heights between rows, or vice versa. The stack is per-row scratch; the heights deliberately carry over.

Full Solution — all languages

class Solution:
    def maximalRectangle(self, grid):
        if not grid or not grid[0]:
            return 0
        C = len(grid[0])
        heights = [0] * C
        best = 0
        for row in grid:
            for c in range(C):
                heights[c] = heights[c] + 1 if row[c] == '1' else 0
            stack = []
            for i in range(C + 1):
                h = 0 if i == C else heights[i]
                while stack and heights[stack[-1]] >= h:
                    top = stack.pop()
                    width = i - stack[-1] - 1 if stack else i
                    best = max(best, heights[top] * width)
                stack.append(i)
        return best
Asked at Sprinklr
SensAI
Beta
Tap the mic to stop voice mode