Skip to problem
←

Maximal Rectangle

Hard 0 attempts

Given a matrix containing the characters "0" and "1", find the largest rectangle made entirely of "1" cells. Its sides must follow the grid: choose consecutive rows and consecutive columns without skipping cells.

Return its area, not its coordinates. A rectangle may have different height and width. If there are no "1" cells, return 0.

Function contract

Implement maximalRectangle(matrix). Receive a nonempty rectangular matrix of string characters "0" and "1", not numeric values.

Output: Return the area of the largest all-ones rectangle, or 0 if no cell contains "1".

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

Example 2

Input
matrix = [["0"]]
Output
0
Visual Aid
Largest rectangle in Example 1
Highlighted rectangle has area 6101001011111111100102 × 3 = 6 cellsReturn 6Every enclosed cell contains "1".

The outlined region spans two rows and 3 columns. Its area is 6.

Constraints
  • 1 <= rows, cols <= 200
  • matrix[i][j] is '0' or '1'

Histogram per Row + Largest Rectangle in Histogram

For each row, accumulate consecutive ones in each column, resetting the height to zero at a zero cell. Treat these heights as a histogram. A non-decreasing stack of column indices finds its maximum rectangle: when a shorter bar arrives, pop taller bars and use the remaining stack top to locate the left boundary. A sentinel iteration flushes the stack. Each column is pushed and popped at most once per row.

javascript
function maximalRectangle(matrix) {
  if (!matrix.length) return 0;
  const n = matrix[0].length, heights = Array(n).fill(0);
  let max = 0;
  for (const row of matrix) {
    for (let j = 0; j < n; j++) heights[j] = row[j] === '1' ? heights[j] + 1 : 0;
    max = Math.max(max, largestRect(heights));
  }
  return max;
}
function largestRect(h) {
  const stack = [], n = h.length;
  let max = 0;
  for (let i = 0; i <= n; i++) {
    while (stack.length && (i === n || h[i] < h[stack[stack.length-1]])) {
      const height = h[stack.pop()];
      const width = stack.length ? i - stack[stack.length-1] - 1 : i;
      max = Math.max(max, height * width);
    }
    stack.push(i);
  }
  return max;
}

Time: O(mn) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript