sagelearnai

Maximal Rectangle

Difficulty: Hard · Pattern: Stack & Monotonic Stack · LeetCode #85

Given a binary matrix of "0"/"1" characters, return the area of the largest rectangle containing only 1s.

Examples

text
[["1","0","1","0","0"],
 ["1","0","1","1","1"],
 ["1","1","1","1","1"],
 ["1","0","0","1","0"]]   →  6
[["0"]]                   →  0

Hints

  1. For each row, compute how many consecutive 1s stand above each column, ending at this row. That's a histogram.
  2. Run Largest Rectangle in Histogram (monotonic stack) on each row's histogram.

Approach

Keep heights[c]: the number of consecutive 1s ending at the current row in column c (reset to 0 on a "0"). Each row's heights form a histogram whose largest rectangle (computed with an increasing stack in O(n)) is a candidate. The maximum over rows is the answer. O(rows × cols).

Complexity

Time: O(rows × cols). Space: O(cols).

Python solution
def maximalRectangle(matrix):
    if not matrix:
        return 0
    n = len(matrix[0])
    heights, best = [0] * n, 0
    for row in matrix:
        for c in range(n):
            heights[c] = heights[c] + 1 if row[c] == "1" else 0
        st = []
        for i, h in enumerate(heights + [0]):
            while st and heights[st[-1]] > h:
                j = st.pop()
                left = st[-1] if st else -1
                best = max(best, heights[j] * (i - left - 1))
            st.append(i)
    return best
JavaScript solution
function maximalRectangle(matrix) {
  if (!matrix.length) return 0;
  const n = matrix[0].length, heights = new Array(n).fill(0); let best = 0;
  for (const row of matrix) {
    for (let c = 0; c < n; c++) heights[c] = row[c] === '1' ? heights[c] + 1 : 0;
    const st = [];
    for (let i = 0; i <= n; i++) {
      const h = i === n ? 0 : heights[i];
      while (st.length && heights[st[st.length - 1]] > h) {
        const j = st.pop(), left = st.length ? st[st.length - 1] : -1;
        best = Math.max(best, heights[j] * (i - left - 1));
      }
      st.push(i);
    }
  }
  return best;
}