834. Find the largest empty square and rectangle in an occupancy grid
An occupancy mask marks free cells with 0 and blocked cells with 1. You want to know how big a region you can place in the free space.
Write largest_empty_regions(grid) that returns a list [square_area, rect_area]: the area of the largest axis-aligned square made only of 0 cells, and the area of the largest axis-aligned rectangle made only of 0 cells. If there is no 0 cell, both are 0.
def largest_empty_regions(grid)Example 1
for grid [[0, 0, 1], [0, 0, 0], [1, 0, 0]] the result is [4, 4]: the top left 2 by 2 block is free.
Example 2
for grid [[0, 0, 0, 0], [1, 1, 0, 0]] the result is [4, 4]: a 2 by 2 square on the right, and the 1 by 4 top row also has area 4.
Constraints
- 0 <= rows, cols <= 300
- Cells are 0 or 1.
Hint 1
Square: 1 + min(up, left, up-left) on free cells.
Hint 2
Rectangle: build column heights row by row.
Hint 3
Use a sentinel height 0 at the end of each row to flush the stack.
Common mistakes
- Returning the square side instead of its area.
- Forgetting to reset a column height to 0 on a blocked cell.
- Popping only strictly taller bars and then using the wrong left edge.
Understand the idea
Both halves are classic grid dynamic programs. The square uses a local min of three neighbours because a square of side k at a corner needs squares of side k - 1 above, left and diagonal. The rectangle reduces a 2D search to one histogram per row: heights grow by one on free cells and reset to 0 on blocked ones. In a histogram, each bar is the shortest bar of exactly one maximal rectangle, and a monotonic stack finds the left and right limits of every bar in one pass.