Maximal Square solution explained
Maximal Square asks for the area of the largest square made only of 1s in a grid of 0s and 1s. Let side(r, c) be the side of the biggest all-ones square whose bottom-right corner is cell (r, c): it is 0 on a 0 cell, and otherwise 1 plus the smallest of the values above, to the left and diagonally up-left. The answer is the largest side squared, found in O(rows × cols) time with one row of memory.
By Evin JohnPublished 6 min read
The problem, restated
You are given a rectangular grid where each cell holds 0 or 1. Find the largest square block whose cells are all 1 and return how many cells it covers. A single 1 counts as a 1 by 1 square; a grid with no 1s at all gives 0. Some versions store the cells as the characters "0" and "1"; compare against "1" in that case and nothing else changes.
| c0 | c1 | c2 | c3 | |
|---|---|---|---|---|
| r0 | 0 | 1 | 1 | 0 |
| r1 | 1 | 1 | 1 | 1 |
| r2 | 1 | 1 | 1 | 1 |
| r3 | 1 | 1 | 1 | 1 |
| r4 | 0 | 1 | 0 | 1 |
The answer here is 9. Rows 1 to 3 are all ones, so two different 3 by 3 blocks fit (columns 0 to 2 and columns 1 to 3). There is no 4 by 4 block: every set of four consecutive rows includes row 0 or row 4, and both contain zeros in the way.
Brute force
def largest_square_brute(grid):
"""Try every top-left corner and every size. Roughly O(r * c * s^3)."""
rows, cols = len(grid), len(grid[0])
best = 0
for r in range(rows):
for c in range(cols):
size = 1
while r + size <= rows and c + size <= cols and all(
grid[i][j] == 1
for i in range(r, r + size)
for j in range(c, c + size)
):
best = max(best, size)
size += 1
return best * bestFor each of the R × C corners, it tries sizes up to S = min(R, C) and checks up to S² cells per size. In a grid full of ones, that is roughly R · C · S³ cell checks. The waste: a square of side 3 is checked from scratch even though you just confirmed the side-2 square inside it.
The DP idea
Anchor squares at their bottom-right corner instead of the top-left. A square of side k ending at (r, c) exists exactly when the cell itself is 1 and squares of side k - 1 end at the cell above, the cell to the left and the cell up-left. Those three overlapping squares cover everything except the corner cell. So the biggest square ending at (r, c) is one more than the smallest of those three neighbors. One weak neighbor limits the whole square.
def largest_square(grid):
"""side[c] = side of the largest all-ones square whose bottom-right is (r, c)."""
cols = len(grid[0])
side = [0] * (cols + 1) # side[c + 1] is column c; side[0] stays 0
best = 0
for row in grid:
diag = 0 # value up and to the left, from the previous row
for c in range(cols):
above = side[c + 1]
if row[c] == 1:
side[c + 1] = 1 + min(above, side[c], diag)
best = max(best, side[c + 1])
else:
side[c + 1] = 0
diag = above
return best * bestfunction largestSquare(grid) {
const cols = grid[0].length;
const side = new Array(cols + 1).fill(0);
let best = 0;
for (const row of grid) {
let diag = 0;
for (let c = 0; c < cols; c++) {
const above = side[c + 1];
if (row[c] === 1) {
side[c + 1] = 1 + Math.min(above, side[c], diag);
best = Math.max(best, side[c + 1]);
} else {
side[c + 1] = 0;
}
diag = above;
}
}
return best * best;
}The only fiddly part of the one-row version is the diagonal. When you are about to overwrite side[c + 1], the value up-left is the old side[c], but side[c] was already overwritten for the current row. So save the old value of each slot (above) before overwriting it, and hand it on as the next column's diagonal.
A trace
| Row | c0 | c1 | c2 | c3 | Note |
|---|---|---|---|---|---|
| r0 | 0 | 1 | 1 | 0 | The first row can only hold 1 by 1 squares |
| r1 | 1 | 1 | 2 | 1 | (1, 2): top 1, left 1, up-left 1, so 2 |
| r2 | 1 | 2 | 2 | 2 | (2, 1): top 1, left 1, up-left 1, so 2 |
| r3 | 1 | 2 | 3 | 3 | (3, 3): top 2, left 3, up-left 2, so min + 1 = 3 |
| r4 | 0 | 1 | 0 | 1 | Zeros reset their slots; the best side stays 3 |
Cost
| Approach | Time | Extra memory |
|---|---|---|
| Grow from every corner | About O(R · C · S³) worst case | O(1) |
| Brute force with a 2D prefix sum to test squares | O(R · C · S) | O(R · C) |
| DP with a full table | O(R · C) | O(R · C) |
| DP with one row (above) | O(R · C) | O(C) |
Edge cases
- All zeros: 0.
- A single 1 anywhere: 1.
- One row or one column: at most 1, since a square needs equal width and height.
- All ones in an R by C grid: min(R, C) squared.
- Character cells: compare with "1", not the number 1, or every cell looks like a 0.
Where answers go wrong
- Returning the side length instead of the area.
- Taking the maximum of the three neighbors instead of the minimum.
- In the one-row version, reading the up-left value after it has been overwritten.
- Confusing squares with rectangles. The largest all-ones rectangle is a different, harder problem that uses a stack over histogram heights.
- Forgetting that a 0 cell must reset its slot to 0, not leave the previous row's value.
How to explain it out loud
Fictional example
- Candidate
- I will define side(r, c) as the largest all-ones square whose bottom-right corner is at r, c. The answer is the max of that, squared.
- Candidate
- If the cell is 1, a square of side k ending here needs squares of side k - 1 ending above, to the left and up-left. Those three cover everything but the corner. So side is one plus the minimum of the three.
- Interviewer
- Why the minimum and not the maximum?
- Candidate
- Because a hole anywhere in the square breaks it. The neighbor with the smallest square is where the nearest 0 is, so it caps the size.
Same idea, other problems
- Count every all-ones square in the grid. Sum the side values instead of taking their maximum: a cell with side 3 is the corner of three squares.
- Largest plus sign or cross of ones. Four direction tables of run lengths, then a minimum per cell.
- Largest rectangle of ones. Build column heights row by row and solve the largest rectangle in a histogram with a stack.
Related walkthroughs
Triangle folds two neighbors into each position; this problem folds three. Unique Paths II is the counting version of grid DP. For a problem where the obvious window idea fails and a stack does the work, see Longest Valid Parentheses. The coding problems hub lists the rest.
Using Natively while you practice
Interviewers often stop you at "why the minimum?", and a crisp one-sentence answer matters more than the code. Practice saying it aloud with Natively transcribing on your Mac or Windows computer, then read back what you actually said. If you get stuck on a grid variant during study time, screenshot it and ask for the definition of the table rather than the code. The AI assistant for coding interviews page covers the coding features.
Questions people ask
How do you solve Maximal Square?
Let side(r, c) be the largest all-ones square ending at (r, c). On a 1 cell it is 1 plus the minimum of the values above, left and up-left; on a 0 cell it is 0. Return the largest side squared.
Why take the minimum of the three neighbors?
The three neighboring squares together cover the candidate square except its corner, and any 0 inside breaks it, so the smallest neighbor limits the size.
What is the complexity of Maximal Square?
O(rows × cols) time. One row of the table plus a saved diagonal value gives O(cols) extra memory.
Does Maximal Square return the side or the area?
The area. Track the largest side and square it at the end.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
