Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
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: The maximal rectangle is shown in the above picture.
Example 2:
Input: matrix = [["0"]] Output: 0
Example 3:
Input: matrix = [["1"]] Output: 1
Constraints:
rows == matrix.lengthcols == matrix[i].length1 <= row, cols <= 200matrix[i][j] is '0' or '1'.Problem Overview: Maximal Rectangle asks you to find the largest rectangle containing only 1s in a binary matrix. The rectangle must be formed by contiguous cells. The challenge is efficiently evaluating all possible rectangles without checking every submatrix.
Approach 1: Histograms and Monotonic Stack (O(m*n) time, O(n) space)
The key insight is that every row can be treated as the base of a histogram. As you iterate through the matrix row by row, maintain a heights array where heights[j] counts consecutive 1s ending at the current row for column j. Each row converts the matrix into a histogram problem. You then compute the largest rectangle in that histogram using a stack, specifically a monotonic stack that keeps increasing bar heights.
The stack stores column indices. When the current height becomes smaller than the height at the stack top, you pop indices and compute rectangle areas where the popped bar becomes the limiting height. The width is determined using the next smaller element to the left and right. This avoids recomputing areas for every possible width. Since each column index is pushed and popped once per row, the overall complexity becomes O(m*n) time with O(n) extra space.
Approach 2: Dynamic Programming Boundaries (O(m*n) time, O(n) space)
This method maintains three arrays for each row: height, left, and right. The height array tracks consecutive vertical 1s just like the histogram approach. The left array stores the leftmost boundary where the rectangle can extend, while right stores the right boundary.
During each row scan, update height by incrementing for 1s and resetting for 0s. Then sweep from left to right to update the left boundary and from right to left to update right. The area at column j becomes (right[j] - left[j]) * height[j]. Tracking these boundaries effectively builds valid rectangles without explicitly using a stack. The approach relies heavily on dynamic programming and works in O(m*n) time with O(n) space.
Recommended for interviews: The histogram + monotonic stack approach is the one most interviewers expect. It shows that you can reduce a 2D rectangle problem into a sequence of 1D histogram problems and apply a classic stack pattern. Mentioning the brute-force rectangle enumeration demonstrates understanding of the problem space, but implementing the histogram stack solution proves strong algorithmic skills with arrays, stacks, and matrix transformations.
This approach is inspired by transforming the binary matrix row by row into histograms. For each row, consider it as the base and calculate the height of '1's found upwards in each column (until a '0' is encountered, resetting the height). Using these heights, treat each row as a histogram problem where you need to find the largest rectangular area. You can apply the 'Largest Rectangle in Histogram' algorithm using a stack for efficient processing.
The approach uses a stack-based method to calculate the largest rectangle in every row's histogram representation. Each row computes its respective histogram heights, and a monotonically increasing stack is used to calculate the maximum possible area efficiently.
JavaScript
Java
Time Complexity: O(n * m) where n is the number of rows and m is the number of columns.
Space Complexity: O(m), used by the 'heights' array and stack.
This approach involves using dynamic programming (DP) to compute not only the heights but also left and right boundaries for each row's histogram. By maintaining arrays for each row, you can determine the maximum potential width of a rectangle starting from each point and thereby compute the largest rectangle area efficiently.
In this C++ solution, three vectors are maintained for each row: height, left, and right. These vectors help in calculating the maximal rectangle that can be formed by treating each row as a histogram. Dynamic programming ensures that for each iteration all possible rectangle areas are computed while respecting prior computed values.
C#
Time Complexity: O(n * m) because each cell is processed in constant time.
Space Complexity: O(m), due to extra arrays for heights, and boundaries.
| Approach | Complexity |
|---|---|
| Approach Using Histograms and Stack | Time Complexity: O(n * m) where n is the number of rows and m is the number of columns. |
| Dynamic Programming Approach | Time Complexity: O(n * m) because each cell is processed in constant time. |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Histograms + Monotonic Stack | O(m*n) | O(n) | Best general solution; commonly expected in coding interviews |
| Dynamic Programming Boundaries | O(m*n) | O(n) | Useful if you prefer explicit boundary tracking instead of stack logic |
LARGEST RECTANGLE IN HISTOGRAM - Leetcode 84 - Python • NeetCode • 287,824 views views
Watch 9 more video solutions →Practice Maximal Rectangle with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor