Python coding

Largest square of ones

grid is a list of equal-length strings made of the characters 0 and 1. Return the area of the largest square, with its sides along the rows and columns, whose cells are all 1. If the grid has no 1 at all, return 0.

The grid has 1 to 200 rows and 1 to 200 columns. Aim for O(rows · columns) time.

Besides the tests, one large input (a 100×100 grid of ones) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • largest_square(["10111","11111","01111","11011"]) → 9
  • largest_square(["1111","1111"]) → 4
  • largest_square(["10","01"]) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Name each square by its bottom-right cell. A square of side k ends at a 1 only if squares of side k − 1 end at the cells above, to the left and up-left.

Hint 2

So side = 1 + min(up, left, up_left) at a 1, and 0 at a 0. One row of sides is enough; keep the largest and return its square, the area.

Solution and why it works
pythonO(R·C), R×C grid · O(C)
def largest_square(grid: list[str]) -> int:
    side = [0] * (len(grid[0]) + 1)      # side[c + 1]: largest all-1 square whose bottom-right is column c
    best = 0
    for row in grid:
        diag = 0                         # side[c] of the row above, before this row overwrote it
        for c, cell in enumerate(row):
            up = side[c + 1]
            side[c + 1] = 1 + min(up, side[c], diag) if cell == "1" else 0
            diag = up
            best = max(best, side[c + 1])
    return best * best                   # the area, not the side

The square ending at a cell is capped by its neighbors above, left and up-left: if each ends a square of side at least k − 1, those three squares plus the cell cover the whole k × k block, and the smallest of them is the bottleneck. So each cell costs O(1), keeping one row. Brute force grows a square from every corner and rechecks each new edge, about O(R·C·k²). Return the area, not the side.

Related lab: Big-O growth