Maximal Rectangle solution explained

Maximal Rectangle asks for the area of the largest rectangle made only of 1 cells in a grid of 0s and 1s. Treat each row as the floor of a histogram whose bar heights count the consecutive 1s ending at that row, then find the largest rectangle in that histogram with an increasing stack of indexes. Every row takes O(columns) time, so the whole grid takes O(rows × columns) time and O(columns) memory.

By Published 8 min read

The problem, restated

You get a grid with R rows and C columns where every cell is 0 or 1. Here the rows arrive as strings such as "10110". Among all rectangles whose sides follow the grid lines and whose cells are all 1, return the largest area, counted in cells. An empty grid, or a grid with no 1s, gives 0.

Examples written for this page
Grid (one string per row)Largest areaWhere it is
["10110", "11110", "01111", "11011"]6Rows 2 and 3, columns 2 to 4 (counting from 1)
["0110", "1111", "0111"]6Rows 1 to 3, columns 2 and 3
["1", "1", "1", "0", "1"]3The top three cells of the single column
["111", "111"]6The whole grid
["000"]0No 1 cells
Examples written for this page. Scroll sideways on a small screen.

What the interviewer is testing

This problem is a reduction test. The grid looks two-dimensional and intimidating, and the key move is to see that fixing the bottom row of a rectangle turns the rest into a one-dimensional histogram problem. After that, the interviewer checks whether you know, or can derive, the monotonic stack for histograms, and whether you can explain why each bar is pushed and popped once. Many interviewers ask the histogram problem first and this one as the follow-up.

Follow-ups

  • Largest square instead of rectangle. A simpler DP: side[r][c] = 1 + min of the three neighbors above and to the left.
  • Return the corners, not just the area. When a bar is popped, its left edge, right edge and height define the rectangle; record them along with the area.
  • Rows much longer than the number of rows. Build histograms down the columns instead, so the stack runs over the shorter side.
  • Count all-1 rectangles instead of finding the largest. A different stack technique, since you add counts rather than take a maximum.

Brute force

Pick every top-left corner and every bottom-right corner and check whether all cells between them are 1. Checking cell by cell makes this O(R³ · C³). A 2D prefix sum lets you count the 1s in any rectangle in O(1), bringing it down to O(R² · C²), which still means billions of checks for a 200 by 200 grid. It is worth describing because it gives you a correct reference, then moving on.

def maximal_rectangle_slow(grid):
    rows = len(grid)
    cols = len(grid[0]) if rows else 0
    pre = [[0] * (cols + 1) for _ in range(rows + 1)]
    for r in range(rows):
        for c in range(cols):
            pre[r + 1][c + 1] = (pre[r][c + 1] + pre[r + 1][c] - pre[r][c]
                                 + (grid[r][c] == "1"))
    best = 0
    for top in range(rows):
        for left in range(cols):
            for bottom in range(top, rows):
                for right in range(left, cols):
                    area = (bottom - top + 1) * (right - left + 1)
                    ones = (pre[bottom + 1][right + 1] - pre[top][right + 1]
                            - pre[bottom + 1][left] + pre[top][left])
                    if ones == area:
                        best = max(best, area)
    return best
Python: every rectangle, counted with a 2D prefix sum.

Step one: a histogram per row

Fix a row as the bottom edge of the rectangle. For each column, count how many 1s stack up directly above that row, including it. That count is a bar height. Any all-1 rectangle whose bottom edge is this row is exactly a rectangle under those bars, so the best answer for this row is the largest rectangle in the histogram. Heights carry over from the row above: add 1 for a 1 cell, reset to 0 for a 0 cell.

Heights for the first example, row by row
RowCellsHeightsBest rectangle in this histogram
110110[1, 0, 1, 1, 0]2
211110[2, 1, 2, 2, 0]4
301111[0, 2, 3, 3, 1]6
411011[1, 3, 0, 4, 2]4
Heights for the first example, row by row. Scroll sideways on a small screen.

Step two: largest rectangle in a histogram

For each bar, the widest rectangle at that bar's height stretches left and right until it meets a shorter bar. A stack of indexes with increasing heights finds both edges in one pass. When the current bar is shorter than the bar on top of the stack, that top bar cannot extend further right, so pop it: its right edge is the current index, and its left edge is just after the new top of the stack, because everything between was taller. A 0 appended at the end flushes whatever remains.

def largest_in_histogram(heights):
    stack = []  # indexes whose heights increase from bottom to top
    best = 0
    for i, h in enumerate(heights + [0]):
        while stack and heights[stack[-1]] >= h:
            top = stack.pop()
            left = stack[-1] + 1 if stack else 0
            best = max(best, heights[top] * (i - left))
        stack.append(i)
    return best

def maximal_rectangle(grid):
    if not grid:
        return 0
    heights = [0] * len(grid[0])
    best = 0
    for row in grid:
        for c, cell in enumerate(row):
            heights[c] = heights[c] + 1 if cell == "1" else 0
        best = max(best, largest_in_histogram(heights))
    return best
Python: histogram with a monotonic stack, then one histogram per row.
function largestInHistogram(heights) {
  const stack = [];
  let best = 0;
  for (let i = 0; i <= heights.length; i++) {
    const h = i === heights.length ? 0 : heights[i];
    while (stack.length > 0 && heights[stack[stack.length - 1]] >= h) {
      const top = stack.pop();
      const left = stack.length > 0 ? stack[stack.length - 1] + 1 : 0;
      best = Math.max(best, heights[top] * (i - left));
    }
    stack.push(i);
  }
  return best;
}

function maximalRectangle(grid) {
  if (grid.length === 0) return 0;
  const heights = new Array(grid[0].length).fill(0);
  let best = 0;
  for (const row of grid) {
    for (let c = 0; c < row.length; c++) {
      heights[c] = row[c] === "1" ? heights[c] + 1 : 0;
    }
    best = Math.max(best, largestInHistogram(heights));
  }
  return best;
}
JavaScript: the same two steps.

Trace the third row of the first example, heights [0, 2, 3, 3, 1]. Push 0, then 1 (height 2), then 2 (height 3). At index 3, height 3 is not taller than the top's 3, so pop index 2: left edge is 2, width 3 - 2 = 1, area 3. Push 3. At index 4, height 1 pops index 3 (left edge 2, width 2, area 6), then index 1 (left edge 1, width 3, area 6). The final 0 pops index 4 (width 4, area 4) and index 0 (area 0). The best is 6.

Popping on equal heights, the >= in the loop, is a choice. It means a bar of equal height may report a narrower width than it really has, but the last bar of that equal run is popped later with the full width, so the maximum is still found.

Complexity

R rows, C columns
ApproachTimeExtra memory
Every rectangle, checked cell by cellO(R³ · C³)O(1)
Every rectangle with a 2D prefix sumO(R² · C²)O(R · C)
Histogram per row with a stackO(R · C)O(C)
R rows, C columns. Scroll sideways on a small screen.

The stack step is linear because each index is pushed once and popped at most once per row, no matter how many pops a single step performs.

Edge cases

  • Empty grid, or rows of length 0: 0.
  • All zeros: 0. All ones: R × C.
  • A single row or a single column, where the answer is the longest run of 1s.
  • Equal heights side by side, which exercise the >= choice.
  • Rows given as lists of characters or numbers instead of strings; compare against the right type.

Common mistakes

  • Forgetting the trailing 0, so bars left on the stack are never measured.
  • Using the popped index as the left edge instead of the index after the new stack top.
  • Not resetting a height to 0 on a 0 cell, which lets rectangles pass through gaps.
  • Comparing the cell to the number 1 when the grid holds the character "1" (or the other way round).
  • Trying to grow rectangles from each cell in every direction, which is easy to get wrong and slower.

How to explain it out loud

Fictional example

Reducing two dimensions to one
Candidate
If I fix the bottom row of the rectangle, each column contributes a run of 1s going up. Those runs are bar heights, and the rectangle is a rectangle under a histogram.
Candidate
For a histogram, each bar's best rectangle extends until a shorter bar on each side. An increasing stack of indexes gives me both edges: when a shorter bar arrives, I pop and measure.
Candidate
Updating heights row by row is O(C), and the stack is O(C) per row, so the whole thing is O(R times C) with one array of heights.

Number of Islands also works on a grid of 0s and 1s, but asks about connected regions instead of rectangles. Unique Paths is a grid DP where each cell builds on the row above, the same way heights do here. Count of Smaller Numbers After Self is another problem where a clever ordering turns a quadratic scan into near-linear work, and Best Time to Buy and Sell Stock III uses left and right running values much like the stack finds left and right edges.

Practicing with Natively

The histogram trace is the part that slips under pressure, so rehearse it aloud with a small example. During practice on Mac or Windows, Natively can read a grid problem from a screenshot and suggest an approach to check yours against, and the transcript of your mock interview shows where your explanation of the pop step got vague. Read about the AI interview assistant.

Questions people ask

How do you solve Maximal Rectangle?

Keep a height per column counting consecutive 1s ending at the current row, then find the largest rectangle in that histogram with an increasing stack of indexes. The best over all rows is the answer.

How does the largest rectangle in a histogram stack work?

Keep indexes with increasing heights. When a shorter bar arrives, pop the taller ones: each popped bar's rectangle ends at the current index and starts just after the new stack top.

What is the time complexity of Maximal Rectangle?

O(rows times columns) time and O(columns) extra memory, because each row's histogram is processed in linear time.

Is Maximal Rectangle the same as Maximal Square?

No. Maximal Square has a simpler DP using the three neighbors of each cell; rectangles need the histogram reduction.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP