Maximal Rectangle

Largest all-1 rectangle in a binary matrix — per-row "max rectangle in histogram" via monotonic stack.

Hard
Time O(m * n) Space O(n)
LeetCode
5 min read
dp monotonic-stack

Problem#

Find the largest rectangle of 1s in a binary matrix.

Examples#

  • [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]6

Constraints#

  • 1 <= m, n <= 200.

Approach#

For each row, maintain a running “height” array (consecutive 1s ending at this row per column). Apply the largest-rectangle-in-histogram routine (monotonic stack) to the heights.

Solution#

Maximal Rectangle
class Solution {
public:
int maximalRectangle(vector<vector<char>>& matrix) {
if (matrix.empty()) return 0;
int m = matrix.size(), n = matrix[0].size();
vector<int> heights(n, 0);
int best = 0;
for (int r = 0; r < m; ++r) {
for (int c = 0; c < n; ++c)
heights[c] = matrix[r][c] == '1' ? heights[c] + 1 : 0;
best = max(best, largestRectangle(heights));
}
return best;
}
private:
int largestRectangle(vector<int>& h) {
h.push_back(0);
stack<int> st;
int best = 0;
for (int i = 0; i < (int)h.size(); ++i) {
while (!st.empty() && h[st.top()] > h[i]) {
int top = st.top(); st.pop();
int width = st.empty() ? i : i - st.top() - 1;
best = max(best, h[top] * width);
}
st.push(i);
}
h.pop_back();
return best;
}
};

Editorial#

The reduction: every all-1 rectangle in the matrix has some bottom row r; viewing column-heights ending at row r as a histogram, the rectangle is the largest one in that histogram. So the m-row matrix is m histogram problems.

Complexity#

  • Time: O(m * n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.