Magicsheet logo

Maximal Square

Medium
70.4%
Updated 6/1/2025

Maximal Square

What is this problem about?

The Maximal Square problem provides a 2D binary matrix filled with 0s and 1s. Your objective is to find the largest square sub-grid that contains only 1s and return its area. For example, if you find a 3×33 \times 3 block of all 1s, the returned area should be 9.

Why is this asked in interviews?

This is the textbook problem for teaching 2D Dynamic Programming. It is asked frequently because its optimal solution is incredibly elegant and requires very little code, but deducing the recurrence relation requires a strong grasp of geometric overlap and state caching. It separates candidates who brute-force O(N4)O(N^4) solutions from those who understand spatial state accumulation in O(N2)O(N^2) time.

Algorithmic pattern used

This problem relies purely on a 2D Dynamic Programming pattern. We define a DP matrix where dp[i][j] represents the side length of the maximum square whose bottom-right corner is at cell (i, j). If matrix[i][j] is '1', the size of the square ending there is determined by its top, left, and top-left neighbors. If any of those neighbors have a 0, the current square cannot be larger than 1. The recurrence relation is: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 You keep track of the maximum value seen in the DP table, and the final area is max_len * max_len.

Example explanation

Matrix:

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

Let's build the DP table: Row 0: [1, 0, 1, 0] Row 1: [1, 1, 1, 1] -> Using formula: dp[1][1] is min(0, 1, 1) + 1 = 1. dp[1][2] is min(1, 1, 0) + 1 = 1. dp[1][3] is min(0, 1, 1) + 1 = 1. Row 2:

  • dp[2][1]: min(1, 1, 1) + 1 = 2. (Square of size 2 ending here!)
  • dp[2][2]: min(1, 1, 1) + 1 = 2.
  • dp[2][3]: min(1, 1, 1) + 1 = 2. The maximum value in the DP table is 2. The maximum area is 2×2=42 \times 2 = 4.

Common mistakes candidates make

Candidates often attempt to solve this by searching for all possible top-left corners and expanding diagonally until they hit a zero, taking O(N3)O(N^3) time. While faster than naive brute force, it's not optimal. Another common error when implementing the DP approach is forgetting to handle the first row and first column correctly, where i-1 or j-1 would result in out-of-bounds exceptions.

Interview preparation tip

For the Maximal Square coding problem, practice optimizing the space complexity. Since calculating dp[i][j] only requires the current row and the previous row, you can reduce the O(M×N)O(M \times N) space complexity to strictly O(N)O(N) by using a 1D array that overwrites itself as you move down the matrix. Mentioning this space optimization will severely impress your interviewer.

Similar Questions