Maximal Rectangle

Find the largest rectangle of 1s in a grid by treating each row as the floor of a bar chart.

Given a grid matrix whose cells hold the characters '0' and '1', return the area of the largest rectangle made only of '1' cells. The area is the number of cells the rectangle covers, and its sides run along the rows and columns of the grid.

Example 1
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: rows 1 and 2, columns 2 to 4.
Example 2
Input: matrix = [["0"]]
Output: 0
Solution

The Idea

Imagine a sheet of squared paper where some squares are shaded. You want to cut out one rectangle with scissors, as large as possible, without any unshaded square in it. The shaded squares are the 1s, and the size of the piece is the area.

In Example 1, the rows are numbered 0 to 3 from the top and the columns 0 to 4 from the left. Rows 1 and 2 both have 1s in columns 2, 3 and 4, so those six cells form a rectangle of area 6. Column 0 is all 1s too, but that strip of four cells only has area 4.

A grid of 4 rows and 5 columns already holds 150 different rectangles: 10 ways to choose a top and a bottom row, times 15 ways to choose a left and a right column. Checking each one cell by cell gets slow as the grid grows. Is there a way to look at fewer of them?

Every rectangle has a bottom row, so we can try each row as the bottom in turn. Take row 2 as the bottom. For each column, count how many 1s stand in an unbroken line from row 2 upward. Column 0 has three (rows 0, 1 and 2), column 1 has one, because row 1 holds a 0 there, and columns 2, 3 and 4 have 3, 2 and 2.

The picture shows both views of Example 1 side by side, with the largest rectangle in orange.

Left: Example 1 as a grid with rows 0 to 3 and cols 0 to 4, and the rectangle of rows 1 to 2, cols 2 to 4 marked in orange, area 6. Right: the heights with row 2 as the bottom, bars of 3, 1, 3, 2 and 2, with height 2 across cols 2 to 4 marked in orange: height 2 times width 3 is 6.

On the left, the orange rectangle covers rows 1 to 2, cols 2 to 4. On the right, under "heights with row 2 as the bottom", each column's count is drawn as a bar standing on row 2: 3, 1, 3, 2 and 2. A chart of side-by-side bars like this is called a histogram.

Any rectangle of 1s whose bottom is row 2 is now a block under these bars. It spans some neighbouring columns, and it can be no taller than the shortest bar among them. Across col 2 to col 4 the shortest bar is 2, so the block is 2 high and 3 wide, area 6: the same orange cells as on the left.

So the grid problem becomes four smaller ones, one per bottom row: find the largest rectangle under a histogram. The answer is the largest of those four.

Solution Approach

Checking every rectangle would work, but it costs too much. The bottom-row view needs three things settled instead: each row's bar heights, the largest rectangle under one histogram, and the bars at the end of a row.

Checking every rectangle

Why not just try all of them? With m rows and n columns there are about m²n²/4 rectangles, and checking one can take up to m × n cell reads. The bottom-row view replaces that with one histogram per row.

Bar heights from one row to the next

Do the heights have to be counted from scratch for each bottom row? No. Keep them in an array with one entry per column. Moving down one row, a '1' adds one to the bar above it, and a '0' sets the bar back to 0, because no rectangle of 1s can pass through that cell.

In Example 1, row 2 gives the bars [3, 1, 3, 2, 2] from the picture. Row 3 is 1, 0, 0, 1, 0, so the bars become [4, 0, 0, 3, 0]: columns 0 and 3 grow by one and the rest drop to 0.

The largest rectangle under one histogram

Which rectangle under the bars is the best? Each rectangle worth measuring is set by one bar: it takes that bar's full height and stretches left and right until a shorter bar stops it. In the picture, the bar at col 3 is 2 high. To its left, col 2 is taller and col 1 is shorter, and to its right col 4 is as tall and then the row ends. So its stretch is col 2 to col 4, area 2 × 3 = 6.

Walking left and right from every bar can take up to n steps per bar. A stack of column numbers does it in one pass instead. Think of it as a pile of cards with a column number on each, where a new card goes on top and only the top card can be taken off, or popped. The pile keeps columns whose bars grow taller from bottom to top. When the next bar is no taller than the bar on top, that top bar cannot stretch further right, so it is popped and measured.

Where does a popped bar's stretch begin? The column now on top of the stack holds the nearest shorter bar to its left, so the stretch starts just after it. If the stack is empty, the stretch starts at col 0. The stretch ends just before the bar that caused the pop. A stack whose entries only grow from bottom to top like this is often called a monotonic stack.

Follow it on [3, 1, 3, 2, 2]. The bar of 1 at col 1 pops col 0, which measures 3 × 1. The bar of 2 at col 3 pops col 2, again 3 × 1. The bar of 2 at col 4 also pops col 3, since equal heights pop too, and col 3 measures only 2 × 2 = 4. That short measure does no harm: col 4 has the same height and will cover the full stretch.

Bars left at the end of the row

After col 4, the stack still holds col 1 and col 4, and nothing has measured them. The code pretends there is one more bar of height 0 just past the last column. It is shorter than every bar, so it pops them all: col 4 measures 2 × 3 = 6 and col 1 measures 1 × 5 = 5.

Java Solution

A helper method, largestInHistogram(h), finds the largest rectangle under the bars in the array h. The method maximalRectangle uses it in these steps:

  1. First, return 0 if the grid has no rows. Otherwise set n to the number of columns, create the array heights with one bar per column, all 0, and set best to 0.
  2. Go through the rows with a loop. Inside it, a second loop over the columns c updates heights[c]: one more than before for a '1', back to 0 for a '0'.
  3. After each row, pass heights to largestInHistogram and keep the larger of its result and best.
  4. Inside the helper, stack holds the pile of column numbers. It is an ArrayDeque, whose push, pop and peek add, remove and read the top column. A loop moves i from 0 to h.length, one step past the last column, and cur is the bar at i, or 0 for that extra step.
  5. While the bar on top of stack is at least cur, pop it into height. The new top, or -1 if stack is empty, is left, so the width is i - left - 1. Keep the largest height times width, then push i.
  6. When all rows are done, return best.

The main method prints the bars and the helper's result for each row of Example 1, then runs both examples. It also tries a single '1', a grid that is all 1s, one column with a 0 in it, and a grid with no rows.

Java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class MaximalRectangle {

    public static int maximalRectangle(char[][] matrix) {
        if (matrix.length == 0) {
            return 0;
        }
        int n = matrix[0].length;
        int[] heights = new int[n];       // 1s stacked up in each column, ending at this row
        int best = 0;
        for (char[] row : matrix) {
            for (int c = 0; c < n; c++) {
                heights[c] = row[c] == '1' ? heights[c] + 1 : 0;
            }
            best = Math.max(best, largestInHistogram(heights));
        }
        return best;
    }

    // Largest rectangle under the bars, with a stack of bar indices whose heights increase.
    static int largestInHistogram(int[] h) {
        Deque<Integer> stack = new ArrayDeque<>();
        int best = 0;
        for (int i = 0; i <= h.length; i++) {
            int cur = i == h.length ? 0 : h[i];   // a bar of height 0 after the end
            while (!stack.isEmpty() && h[stack.peek()] >= cur) {
                int height = h[stack.pop()];
                int left = stack.isEmpty() ? -1 : stack.peek();  // nearest lower bar on the left
                best = Math.max(best, height * (i - left - 1));
            }
            stack.push(i);
        }
        return best;
    }

    static char[][] grid(String... rows) {
        char[][] m = new char[rows.length][];
        for (int r = 0; r < rows.length; r++) {
            m[r] = rows[r].toCharArray();
        }
        return m;
    }

    public static void main(String[] args) {
        char[][] example1 = grid("10100", "10111", "11111", "10010");
        int[] heights = new int[5];
        for (int r = 0; r < example1.length; r++) {
            for (int c = 0; c < 5; c++) {
                heights[c] = example1[r][c] == '1' ? heights[c] + 1 : 0;
            }
            System.out.println("row " + r + ": " + new String(example1[r]) + "  heights "
                    + Arrays.toString(heights) + "  best " + largestInHistogram(heights));
        }
        System.out.println("Example 1: " + maximalRectangle(example1));
        System.out.println("Example 2: " + maximalRectangle(grid("0")));
        System.out.println("[[1]]: " + maximalRectangle(grid("1")));
        System.out.println("two rows of 111: " + maximalRectangle(grid("111", "111")));
        System.out.println("one column 1,1,0,1: " + maximalRectangle(grid("1", "1", "0", "1")));
        System.out.println("no rows: " + maximalRectangle(new char[0][]));
    }
}

The small helper grid only turns strings such as "10100" into rows of characters for the tests. Running the program prints:

Output
row 0: 10100  heights [1, 0, 1, 0, 0]  best 1
row 1: 10111  heights [2, 0, 2, 1, 1]  best 3
row 2: 11111  heights [3, 1, 3, 2, 2]  best 6
row 3: 10010  heights [4, 0, 0, 3, 0]  best 4
Example 1: 6
Example 2: 0
[[1]]: 1
two rows of 111: 6
one column 1,1,0,1: 2
no rows: 0

The line for row 2 shows the bars from the picture, [3, 1, 3, 2, 2], and its best is 6, the answer for Example 1. On row 3 the bars are [4, 0, 0, 3, 0], and the best there is 4: the full column 0, which falls short of 6. Row 1 gives 3, the single row of 1s across columns 2 to 4.

For the grid [["1"], ["1"], ["0"], ["1"]] the result is 2. The 0 in row 2 sets the bar back to 0, so the 1 in row 3 cannot join the two above it. With no rows, the first check returns 0 before matrix[0] is read.

The extra bar of height 0 matters. A version of the helper whose loop stops at i < h.length returns 4 for the bars [3, 1, 3, 2, 2] instead of 6. It also returns 4 for [2, 2, 2], the bars under the second row of the grid with two rows of 111. The bars that should give 6 are still on the stack when that loop ends.

Complexity

For a grid with m rows and n columns, every row costs one update of the bars and one stack pass.

  • Time: O(m × n), because each row updates its n bars once and the helper pushes each of its n + 1 positions once and pops each at most once.
  • Space: O(n), because heights keeps one bar per column and the stack holds at most one entry per position, while the grid itself is only read.

The helper on its own solves Largest Rectangle in Histogram.