← Back to Algorithms, page 5

algorithms-0088 · Medium mid

Maximal square: find the area of the largest square containing only '1' cells in a binary matrix.

Let side[r][c] be the side of the largest all-1 square whose bottom-right corner is (r, c). For a '1' cell it is 1 + min(top, left, top-left); for a '0' cell it is 0. Track the maximum side and return its square. One rolling row with a saved diagonal gives O(R * C) time and O(C) space.

Full answer

Problem

Given an R x C matrix of '0' and '1', return the area of the largest square made only of '1' cells.

Example:

1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0

returns 4 (a 2 x 2 square).

Constraints: 1 <= R, C <= 300.

Brute force

For every cell as the top-left corner, grow the square while all cells inside are '1'. Checking a square of side k cell by cell costs O(k^2), so with k up to min(R, C) the total is O(R * C * min(R, C)^3); checking only the new border when growing brings it to O(R * C * min(R, C)^2).

Optimal approach

  • side[r][c] = 0 if the cell is '0'.
  • Otherwise side[r][c] = 1 + min(side[r-1][c], side[r][c-1], side[r-1][c-1]).
  • Answer: max(side) ** 2.

With one row of length C + 1 (a padding column of zeros): before overwriting row[c], save it as up; the previous up from column c - 1 is the diagonal.

Why it works

A square of side k ending at (r, c) exists exactly when squares of side k - 1 end at the cell above, the cell to the left and the cell diagonally up-left, and (r, c) itself is '1'. Those three overlapping squares together cover the k x k square except the corner. So the largest side is limited by the smallest of the three neighbours, plus one.

Complexity

O(R * C) time, O(C) extra space.

Code

python
import random


def maximal_square(matrix):
    """Area of the largest all-'1' square. side[r][c] = 1 + min(up, left, up-left).
    One rolling row: O(R * C) time, O(C) space."""
    if not matrix:
        return 0
    cols = len(matrix[0])
    row, best = [0] * (cols + 1), 0
    for r in matrix:
        diag = 0                          # side of the up-left neighbour
        for c in range(1, cols + 1):
            up = row[c]
            if r[c - 1] == "1":
                row[c] = 1 + min(up, row[c - 1], diag)
                best = max(best, row[c])
            else:
                row[c] = 0
            diag = up
    return best * best


def brute(matrix):
    if not matrix:
        return 0
    R, C, best = len(matrix), len(matrix[0]), 0
    for r in range(R):
        for c in range(C):
            k = 1
            while r + k <= R and c + k <= C and all(matrix[i][j] == "1" for i in range(r, r + k) for j in range(c, c + k)):
                best = max(best, k)
                k += 1
    return best * best


if __name__ == "__main__":
    m = ["10100", "10111", "11111", "10010"]
    assert maximal_square(m) == 4
    assert maximal_square(["01", "10"]) == 1 and maximal_square(["0"]) == 0 and maximal_square([]) == 0
    assert maximal_square(["111", "111", "111"]) == 9
    rng = random.Random(88)
    for _ in range(500):
        R, C = rng.randint(1, 7), rng.randint(1, 7)
        g = ["".join("1" if rng.random() < 0.7 else "0" for _ in range(C)) for _ in range(R)]
        assert maximal_square(g) == brute(g)
    print("all tests passed")

Save as b88_maximal_square.py and run python3 b88_maximal_square.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty matrix (0). No '1' cells (0). A full matrix (min(R, C) squared). Single row or column (1 if any '1'). Matrices given as integers instead of characters (adjust the comparison).

Pattern

Grid DP where a cell's value comes from its up, left and diagonal neighbours. Related: count all square submatrices of 1s (sum of all side values), largest rectangle of 1s (histogram with a monotonic stack per row), and longest common substring (diagonal-only dependency).

python
import random


def maximal_square(matrix):
    """Area of the largest all-'1' square. side[r][c] = 1 + min(up, left, up-left).
    One rolling row: O(R * C) time, O(C) space."""
    if not matrix:
        return 0
    cols = len(matrix[0])
    row, best = [0] * (cols + 1), 0
    for r in matrix:
        diag = 0                          # side of the up-left neighbour
        for c in range(1, cols + 1):
            up = row[c]
            if r[c - 1] == "1":
                row[c] = 1 + min(up, row[c - 1], diag)
                best = max(best, row[c])
            else:
                row[c] = 0
            diag = up
    return best * best


def brute(matrix):
    if not matrix:
        return 0
    R, C, best = len(matrix), len(matrix[0]), 0
    for r in range(R):
        for c in range(C):
            k = 1
            while r + k <= R and c + k <= C and all(matrix[i][j] == "1" for i in range(r, r + k) for j in range(c, c + k)):
                best = max(best, k)
                k += 1
    return best * best


if __name__ == "__main__":
    m = ["10100", "10111", "11111", "10010"]
    assert maximal_square(m) == 4
    assert maximal_square(["01", "10"]) == 1 and maximal_square(["0"]) == 0 and maximal_square([]) == 0
    assert maximal_square(["111", "111", "111"]) == 9
    rng = random.Random(88)
    for _ in range(500):
        R, C = rng.randint(1, 7), rng.randint(1, 7)
        g = ["".join("1" if rng.random() < 0.7 else "0" for _ in range(C)) for _ in range(R)]
        assert maximal_square(g) == brute(g)
    print("all tests passed")

Rolling row with a padding column and a saved diagonal, cross-checked against growing squares from every cell.

Complexity

Time: O(R * C). Space: O(C). Summing all side values counts every all-1 square submatrix with the same pass.

By level

Fresher: Writes the 2D table with the min-of-three rule and traces a small example. Returns the area rather than the side.

Mid: Rolls the table to one row with a saved diagonal and explains the overlapping-squares argument. Extends it to counting all squares.

Senior: Contrasts the square problem with the largest rectangle (histogram stack per row) and chooses the right tool. Discusses processing very large images row by row with O(C) memory.

Key points

  • side = 1 + min(up, left, diagonal) for a '1' cell
  • '0' cells reset to 0
  • Track the max side and square it
  • Rolling row plus saved diagonal
  • O(R * C)

Common mistakes

  • Returning the side instead of the area
  • Losing the diagonal value when rolling the row
  • Comparing integers with strings
  • Forgetting to reset to 0 on '0' cells

Follow-ups

  • How do you count all square submatrices of 1s?
  • How do you find the largest rectangle of 1s?
  • How would you handle a stream of rows that do not fit in memory?

Tips

  • Explain why the minimum of three neighbours bounds the side
  • Draw the overlapping squares
  • Return the area, not the side

Evaluation rubric

  • Correct recurrence
  • Correct area
  • Space optimization
  • Correct complexity