mediumDynamic ProgrammingMatrixDynamic Programming

Maximal Square

mediumTime: O(m * n)Space: O(m * n)

Recognize the pattern

largest square of 1s in binary matrixextend squares from smaller onescheck three neighbors

Brute force idea

A straightforward first read of Maximal Square is this: For each cell, expand outward checking if the square is all 1s — or. Each cell independently expands. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Maximal Square comes when you notice this: DP: dp[i][j] = side length of largest square with bottom-right at (i,j). If grid[i][j] == 1, dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1. The minimum of the three neighbors determines the largest square you can extend. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Maximal Square is this: A square of side k at (i,j) exists only if squares of side k-1 exist at the top, left, and top-left neighbors. The minimum of those three determines how large the current square can be — the weakest link limits the extension. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

One easy way to drift off course in Maximal Square is this: Not understanding WHY it's the minimum — if any neighbor has a smaller square, that dimension constrains the current square. You can't form a 4×4 square if your left neighbor only supports a 2×2. The fix is usually to return to the meaning of each move, not just the steps themselves.

Dynamic Programming Pattern