medium +25 pts

Maximal rectangle in matrix

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

Write a function `maximal_rectangle(matrix)` that receives a rectangular matrix of integers (each cell is 0 or 1) and returns the area of the largest rectangle that consists entirely of 1s. The rectangle sides must be parallel to the matrix edges. If the matrix is empty (no rows or no columns), return 0. **Input** - `matrix`: list of lists of integers, each element is either 0 or 1. The matrix is rectangular (all rows have the same length). **Output** - An integer: the maximum area of a rectangle composed entirely of 1s. **Examples** - `maximal_rectangle([[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]])` → 6 - `maximal_rectangle([])` → 0 - `maximal_rectangle([[0,0],[0,0]])` → 0 - `maximal_rectangle([[1,1],[1,1]])` → 4

Constraints

- 0 ≤ rows, cols ≤ 200 - Each cell is either 0 or 1 - Time complexity should be O(rows * cols) (a stack-based algorithm is expected) - Do not use any external libraries.

Example

>>> maximal_rectangle([[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]])
6
>>> maximal_rectangle([])
0
>>> maximal_rectangle([[0,0],[0,0]])
0
>>> maximal_rectangle([[1,1],[1,1]])
4
25 points ~30 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think of each row as the base of a histogram where each cell's height is the number of consecutive 1s ending at that cell in that column.
For each row, compute the heights array and find the largest rectangle in a histogram.
Use a stack to compute the largest rectangle in a histogram in O(cols) time.
Keep track of the maximum area encountered across all rows.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.