Skip to problem
←

Largest All-Ones Rectangle

Medium 0 attempts

Given a matrix of numeric 0s and 1s, return the area of its largest rectangle containing only 1s.

Choose consecutive rows and consecutive columns; you cannot skip cells or rotate the rectangle. Its height and width may differ. Return the number of cells, not the coordinates. If there are no 1s, return 0.

In Example 1, the second and third rows each contain four 1s, forming a rectangle of area 2 × 4 = 8.

Function contract

Implement maximumSizeRectangleBinarySubMatrixWithAll1s(matrix). Receive a nonempty rectangular matrix of numeric 0 and 1 values.

Output: Return the largest all-ones rectangle area, or 0 when the matrix contains no 1.

Example 1

Input
matrix = [[0,1,1,0],[1,1,1,1],[1,1,1,1],[1,1,0,0]]
Output
8

Example 2

Input
matrix = [[0]]
Output
0
Visual Aid
Example 1: eight cells
Two rows of four ones form a rectangle of area eight01101111111111002 rows × 4 columnsReturn 8All eight enclosed cells contain 1.

Rows 1–2 and columns 0–3 (zero-based) form the largest all-ones rectangle.

Constraints
  • 1 <= R, C <= 1000
  • matrix[i][j] is 0 or 1

Approach: Histogram per Row + Stack

Build a heights array where heights[j] is the number of consecutive 1s above (inclusive) for each row. Reset a column height to zero when its current cell is zero. Apply the largest-rectangle-in-histogram algorithm using a non-decreasing stack of height indices for each row.

When a shorter height arrives, pop taller bars. The popped height spans from just after the remaining stack top to just before the current column. The -1 sentinel supplies the left boundary when no earlier bar remains. A final zero height flushes pending positive bars. Each index is pushed and popped at most once per row.

javascript
function maximumSizeRectangleBinarySubMatrixWithAll1s(matrix) {
  if (!matrix.length) return 0;
  const n = matrix[0].length;
  const heights = new 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;
    const stack = [-1];
    for (let j = 0; j <= n; j++) {
      const h = j === n ? 0 : heights[j];
      while (stack.length > 1 && heights[stack[stack.length-1]] > h) {
        const height = heights[stack.pop()];
        const width = j - stack[stack.length-1] - 1;
        max = Math.max(max, height * width);
      }
      stack.push(j);
    }
  }
  return max;
}

Time Complexity: O(m × n)

Space Complexity: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript