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 OverviewInput Matrix101010111111Maximal Rectangle FoundLargest Rectangle:Height: 2 rowsWidth: 2 columnsArea: 2 × 2 = 4Transform to histogram problem for each rowUse monotonic stack for O(mn) solutionOptimal: O(mn) time, O(n) space
Understanding the Visualization
1
Input Matrix
Binary matrix with 0s and 1s
2
Find Rectangle
Identify largest rectangle containing only 1s
3
Calculate Area
Return area of the maximal rectangle
Key Takeaway
🎯 Key Insight: Convert 2D rectangle problem into multiple 1D histogram problems using height arrays and monotonic stack
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