Biggest Solid Block in a Binary Grid
Dynamic ProgrammingAuto-graded · 19 test casesLast updated
Find the area of the largest square made only of '1' cells in a grid of character digits, using a dynamic programming recurrence that can be compressed to a single row of state.
Biggest Solid Block in a Binary Grid
You are given a rectangular grid with m rows and n columns. Each cell holds a single-character string, either "0" or "1".
A solid block is a square sub-grid, with sides aligned to the rows and columns, in which every cell is "1". Find the largest solid block and return its area, that is, the number of cells it contains.
If the grid contains no "1" at all, return 0.
Aim for O(m * n) time and no more than O(n) additional memory beyond the input.
Input
grid: a list ofmlists, each withnstrings. Each string is exactly"0"or"1".
Output
- An integer: the area (side length squared) of the largest square consisting only of
"1"cells.
Notes
- The cell values are characters, not integers, so compare them with
"1". - Return the area, not the side length.
- A grid with a single row or a single column can only have blocks of side 1 at most.
Constraints
1 <= m, n <= 300grid[i][j]is either"0"or"1".- All rows have the same length.
Examples
Example 1
Input: largest_solid_block([['1', '0', '1', '0', '0'], ['1', '0', '1', '1', '1'], ['1', '1', '1', '1', '1'], ['1', '0', '0', '1', '0']])
Output: 4
Example 2
Input: largest_solid_block([['0', '1'], ['1', '0']])
Output: 1
Example 3
Input: largest_solid_block([['0']])
Output: 0
Hints
Hint 1
For each cell, ask: what is the side of the largest all-ones square whose bottom-right corner is exactly this cell? Every square has exactly one such corner.
Hint 2
If the cell is '1', that side equals 1 + the minimum of the answers for the cell above, the cell to the left, and the cell diagonally up-left. If it is '0', the answer is 0.
Hint 3
Each row only depends on the previous row and on the cells already computed in the current row. Keep one array, and save the old value of the cell you are about to overwrite, because it becomes the diagonal value for the next column.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let s[i][j] be the side length of the largest all-ones square whose bottom-right corner is cell (i, j). Every square has exactly one bottom-right corner, so the answer is the largest s[i][j] over all cells, squared.
Recurrence:
- If
grid[i][j] == "0", thens[i][j] = 0. - Otherwise
s[i][j] = 1 + min(s[i-1][j], s[i][j-1], s[i-1][j-1]), where out-of-range neighbors count as 0.
Why it is correct
- Upper bound. If a square of side
k >= 2ends at(i, j), it contains squares of sidek-1ending at the cell above, the cell to the left, and the diagonal cell. So all three neighbors have value at leastk-1, hence1 + min(...) >= k. - Achievability. Let
tbe the minimum of the three neighbor values. The threet x tsquares ending at those neighbors, together with cell(i, j), cover every cell of the(t+1) x (t+1)square ending at(i, j). All of those cells are"1", so a square of sidet+1really exists.
So the recurrence gives the exact value for every cell.
Reducing memory to O(n)
Row i only needs row i-1 and the already-computed part of row i. Use a single array side of length n + 1, where index 0 is a permanent zero sentinel (this removes first-column boundary checks).
When processing column j:
side[j]still holds the previous row's value: the cell above.side[j-1]was already overwritten with the current row's value: the cell to the left.- The diagonal (previous row, column
j-1) was lost whenside[j-1]was overwritten, so keep it in a variablediag. Before overwritingside[j], store its old value inup; after the update setdiag = upfor the next column. - At the start of each row, reset
diag = 0.
Edge cases
- All zeros:
beststays 0, so the result is 0. - Single row or column: the side never exceeds 1.
- All ones: the side reaches
min(m, n), so the area ismin(m, n)^2. - Cells are strings, so compare with
"1"rather than the integer 1. - Return
best * best, notbest.
Complexity
- Time:
O(m * n), since each cell does constant work. - Space:
O(n)for the one-dimensional array plus a few scalars.
Reference solution
from typing import List
def largest_solid_block(grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
n = len(grid[0])
# side[j + 1] holds the best square side ending at column j;
# side[0] is a permanent zero sentinel for the left border.
side = [0] * (n + 1)
best = 0
for row in grid:
diag = 0 # value of the previous row at column j - 1
for j in range(1, n + 1):
up = side[j] # previous row, same column
if row[j - 1] == "1":
side[j] = min(side[j], side[j - 1], diag) + 1
if side[j] > best:
best = side[j]
else:
side[j] = 0
diag = up
return best * best