Sub topic 12
Maximal Square of Ones
So far, the DP value at each cell has been a count or a cost carried along a path that moves right and down. This chapter changes what a cell remembers. The problem is to find the largest square in a binary matrix that contains only ones and return its area. No path is involved. The same toolkit still applies: define a state per cell, derive a recurrence from nearby cells, pick a fill order, and handle the edges.
This chapter assumes you are comfortable with the earlier chapters on defining a state, writing recurrences, padding boundaries, and the rolling-array technique. It also assumes basic Python and Big-O notation.
The Problem
You are given an m × n matrix of '0' and '1' characters. Find the area of the largest square sub-matrix that contains only '1'.
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0The answer is 4. A 2×2 block of ones covers rows 1–2 and columns 3–4 (zero-indexed). A brute-force approach tries every top-left corner and every side length, then checks each candidate square. That costs up to O(m · n · min(m, n)²). DP cuts this to O(m · n).
Choosing the State
The obvious first idea is "the largest square anywhere inside the sub-matrix matrix[0..i][0..j]." That state is hard to extend, because knowing the best square somewhere above and to the left says nothing about whether the current cell can grow it.
The state that works ties the square to the current cell:
dp[i][j] is the side length of the largest all-ones square whose bottom-right corner is exactly at cell (i, j).
Pinning the corner to the cell makes each value local. If matrix[i][j] is '0', no square can end there, so dp[i][j] = 0. The final answer is the largest value anywhere in the table, squared. It is not dp[m-1][n-1], because the best square can end anywhere.
Deriving the Recurrence
Suppose matrix[i][j] is '1'. Three neighbors matter:
dp[i-1][j], the square ending directly abovedp[i][j-1], the square ending directly to the leftdp[i-1][j-1], the square ending on the upper-left diagonal
The recurrence is:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) if matrix[i][j] == '1'
dp[i][j] = 0 otherwiseWhy the minimum of three is correct
The argument runs in both directions.
Upper bound. Suppose a k×k square of ones ends at (i, j). Remove the bottom row and get a (k−1)×(k−1) square ending at (i-1, j). Remove the right column and get one ending at (i, j-1). Remove both and get one ending at (i-1, j-1). So all three neighbors are at least k−1, which means dp[i][j] cannot be more than 1 plus their minimum.
Lower bound. Let s be the minimum of the three neighbors. The square of side s above, the one to the left, and the one on the diagonal overlap. Together they cover every cell of the (s+1)×(s+1) square ending at (i, j) except the corner itself. The corner is '1' by assumption, so that square is all ones.
Both bounds give the same value, so the recurrence is exact. If you used only two of the neighbors, for example above and left, you would miss a hole in the upper-left region and overcount.
Fill Order and Boundaries
All three dependencies lie in the previous row or earlier in the current row. Row-major order (top to bottom, left to right) therefore computes each of them before it is needed.
For the first row and first column, the neighbors fall outside the grid. You could special-case them (dp = 1 if the cell is '1'), but padding is cleaner. Allocate (m+1) × (n+1) and treat row 0 and column 0 as zeros. Real cell (i-1, j-1) in the matrix maps to dp[i][j].
Implementation
def maximal_square(matrix):
if not matrix or not matrix[0]:
return 0
m, n = len(matrix), len(matrix[0])
dp = [[0] * (n + 1) for _ in range(m + 1)]
best = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if matrix[i - 1][j - 1] == '1':
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
best = max(best, dp[i][j])
return best * best
print(maximal_square([['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']])) # 4Tracing the example
Here is the filled table without the padding row and column:
| row | c0 | c1 | c2 | c3 | c4 |
|---|---|---|---|---|---|
| 0 | 1 | 0 | 1 | 0 | 0 |
| 1 | 1 | 0 | 1 | 1 | 1 |
| 2 | 1 | 1 | 1 | 2 | 2 |
| 3 | 1 | 0 | 0 | 1 | 0 |
At (2, 3) the neighbors are above = 1, left = 1, and diagonal = 1, so the value is 2. At (2, 4) the neighbors are above = 1, left = 2, and diagonal = 1. The minimum is 1, so the value is 2 again. At (3, 3) the left neighbor is 0, so the value drops to 1. The largest value is 2, and the area is 4.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Comparing `matrix[i][j] == 1` when the input holds strings | Every value stays 0 and the answer is 0 | Match the input type (`'1'`), or convert first |
| Returning `best` instead of `best * best` | Off by a square, such as 2 instead of 4 | The problem asks for area |
| Returning `dp[m][n]` | Wrong whenever the best square does not touch the bottom-right corner | Track a running maximum |
| Using `max` instead of `min` | Overcounts squares that contain zeros | The limiting neighbor sets the size |
| Calling `len(matrix[0])` on an empty input | `IndexError` | Guard for empty input first |
Reducing Space to One Row
Only the previous row is read, so the rolling-array technique from the earlier chapter applies. The diagonal adds a wrinkle. When you are about to write dp[j], the old dp[j-1] has already been overwritten with the current row's value. You must save the old value of dp[j] before overwriting it, because it becomes the diagonal for the next column.
def maximal_square_1d(matrix):
if not matrix or not matrix[0]:
return 0
n = len(matrix[0])
dp = [0] * (n + 1)
best = 0
for row in matrix:
prev = 0 # dp[i-1][j-1]; the padding column is always 0
for j in range(1, n + 1):
saved = dp[j] # dp[i-1][j], the diagonal for column j+1
if row[j - 1] == '1':
dp[j] = 1 + min(dp[j], dp[j - 1], prev)
best = max(best, dp[j])
else:
dp[j] = 0
prev = saved
return best * best
print(maximal_square_1d([['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']])) # 4Complexity
Each cell does constant work, so time is O(m · n). The 2D table uses O(m · n) extra space, and the rolling version uses O(n). If you are allowed to modify the input, you can store the values in the matrix itself (after converting to integers) and use O(1) extra space. That saves memory but destroys the input, which callers often do not expect.
Variants and Limits
- Count all square sub-matrices of ones. A cell with
dp[i][j] = kis the bottom-right corner of exactly k all-ones squares, with sides 1 through k. Summing the table gives the total count. - Largest rectangle of ones. The min-of-three trick does not carry over. A rectangle ending at a cell is not determined by one number per neighbor, because its height and width can trade off. The standard approach builds column heights row by row and runs a stack-based "largest rectangle in histogram" pass on each row, in O(m · n) total.
- Largest square of any single value. The same recurrence works if you change the condition to "the cell and all three neighbors hold the same value." Otherwise, the neighbors' squares might be made of a different value than the current cell.
Exercise
Modify the recurrence to count every all-ones square sub-matrix. For the matrix [['0','1','1','1'], ['1','1','1','1'], ['0','1','1','1']], what is the count, and what is the filled dp table?
Show answer
Use the same recurrence and return the sum of all dp values instead of the maximum squared. The table is row 0: 0 1 1 1; row 1: 1 1 2 2; row 2: 0 1 2 3. The sum is 3 + 6 + 6 = 15. That is 10 squares of side 1, 4 of side 2, and 1 of side 3.
Exercise
A teammate writes the recurrence as dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1]) and leaves out the diagonal. Give a small matrix where this returns the wrong area.
Show answer
Use [['1','1'], ['0','1']] arranged so the upper-left region has a hole: [['0','1'], ['1','1']]. At cell (1, 1), above = 1 and left = 1, so the two-neighbor version gives 2 and an area of 4. The diagonal (0, 0) is 0, so no 2×2 square of ones exists. The correct answer is 1.
Exercise
In maximalsquare1d, why is prev reset to 0 at the start of every row instead of carrying over from the previous row?
Show answer
At column j = 1, the diagonal is dp[i-1][0], which is in the padding column and always 0. The value left in prev at the end of the previous row belongs to the last column and has nothing to do with the first column of the new row.