AlgoInsight

DSA problem

Maximal Rectangle

Hard2D Grid DPPattern: 2D Grid DPtop600AmazonMicrosoftGoogleAppleAdobe

Given an m x n binary matrix of '0's and '1's, find the largest rectangle containing only '1's and return its area.

A brute-force enumeration of all rectangles is O(m^2 * n^2) candidate rectangles, each checked in O(m * n), giving an unworkable O(m^3 * n^3) — actually worse. Even with 2-D prefix sums for O(1) area checks, you still face O(m^2 * n^2) rectangles and O((m * n)^2) total work.

The elegant trick reduces the problem to "Largest Rectangle in Histogram" applied to every row. For each row, build an array heights where heights[j] is the count of consecutive '1's in column j ending at the current row (zero if the current cell is '0'). The largest all-ones rectangle whose bottom edge lies on this row equals the largest rectangle in this histogram. Compute it with the classic monotonic-stack algorithm in O(n) per row.

Summing over rows, total time is O(m * n). The heights array can be reused row to row by incrementing entries with '1' and zeroing entries with '0'. The stack-based histogram subroutine adds a sentinel "0" at the right so all remaining bars are popped at the end. Total: O(m * n) time, O(n) space.

Examples

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: A 2-row by 3-column all-ones rectangle in rows 1-2 spanning columns 2-4 has area 6.
Example 2
Input: matrix = [["0"]]
Output: 0
Explanation: No 1s in the grid means no all-ones rectangle exists.
Example 3
Input: matrix = [["1"]]
Output: 1
Explanation: The 1x1 cell itself is the largest rectangle.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingstackmatrixmonotonic-stack

Browse all DSA problems