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.

The rectangle must be axis-aligned (no rotation allowed) and can be anywhere within the matrix.

Example: In matrix [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]], the largest rectangle of 1's has area 6.

Input & Output

Example 1 — Basic Rectangle
$ Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 6
💡 Note: The largest rectangle is from (1,2) to (2,4) with height 2 and width 3, giving area 2×3 = 6
Example 2 — Single Row
$ Input: matrix = [["0","1"]]
Output: 1
💡 Note: The largest rectangle is the single cell (0,1) containing "1", giving area 1
Example 3 — All Zeros
$ Input: matrix = [["0"]]
Output: 0
💡 Note: No rectangle of 1s exists, so the maximum area is 0

Constraints

  • rows == matrix.length
  • cols == matrix[i].length
  • 1 ≤ rows, cols ≤ 200
  • matrix[i][j] is '0' or '1'

Visualization

Tap to expand
Maximal Rectangle Problem INPUT Binary Matrix (4x5) 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 = 1 (filled) = 0 (empty) rows=4, cols=5 ALGORITHM STEPS 1 Build Height Array For each row, compute histogram heights 2 Stack-based Approach Use monotonic stack to find largest rect in histogram 3 Process Each Row Apply histogram algo row by row 4 Track Maximum Keep max area found across all rows Heights at Row 2: 3 1 3 2 2 FINAL RESULT Maximal Rectangle Found 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 OUTPUT 6 Rectangle: 3 cols x 2 rows Area = 3 x 2 = 6 OK - Verified Key Insight: Convert the 2D problem into multiple 1D histogram problems. For each row, build a histogram where each bar height = consecutive 1s above (including current). Then use the "Largest Rectangle in Histogram" algorithm with a monotonic stack. Time: O(rows x cols), Space: O(cols). TutorialsPoint - Maximal Rectangle | Optimal Solution (Stack-based Histogram)
Asked in
Amazon 42 Google 38 Microsoft 29 Facebook 25
269.4K Views
High Frequency
~35 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen