Maximal Square - Problem
Find the Largest Square of 1s in a Binary Matrix

You're given an m x n binary matrix filled with 0s and 1s. Your task is to find the largest square that contains only 1s and return its area.

Think of this matrix as a grid where 1 represents a solid block and 0 represents empty space. You need to find the biggest perfect square you can form using only the solid blocks.

Example:
[[1,0,1,0,0],
[1,0,1,1,1],
[1,1,1,1,1],
[1,0,0,1,0]]


The largest square of 1s has side length 2, so the answer is 4 (area = 2 × 2).

Input & Output

example_1.py — Basic Square
$ Input: [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
💡 Note: The largest square of 1s has side length 2 (in rows 1-2, cols 2-3), so area = 2×2 = 4
example_2.py — Single Cell
$ Input: [["0","1"],["1","0"]]
Output: 1
💡 Note: The largest square of 1s has side length 1 (any single '1'), so area = 1×1 = 1
example_3.py — No Squares
$ Input: [["0"]]
Output: 0
💡 Note: No 1s in the matrix, so no square can be formed, area = 0

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 300
  • matrix[i][j] is '0' or '1'

Visualization

Tap to expand
Maximal Square - Find Largest Square of 1s INPUT Binary Matrix (4x5) 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 1 1 0 Orange = Maximal 2x2 Square Matrix Dimensions m = 4 rows n = 5 columns Find largest square of 1s ALGORITHM STEPS 1 Create DP Table dp[i][j] = max square ending at position (i,j) 2 Initialize Edges First row/col: dp = matrix Copy values directly 3 DP Recurrence If matrix[i][j] == 1: dp[i][j] = 1 + min( dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) 4 Track Maximum maxSide = max of all dp[i][j] Area = maxSide * maxSide Example: dp[2][3] = 1 + min(1,1,1) = 2 This means 2x2 square ends here FINAL RESULT DP Table Values: 1 0 1 0 0 1 0 1 1 1 1 1 1 2 1 1 0 1 2 0 Max value in DP = 2 OUTPUT 4 (2 x 2 = 4) OK - Verified! Area = side^2 = 2^2 = 4 Key Insight: The DP value at each cell represents the side length of the largest square ending at that cell. We take the minimum of three neighbors (top, left, diagonal) because a square can only extend if ALL three directions support it. Time: O(m*n), Space: O(m*n) - can optimize to O(n). TutorialsPoint - Maximal Square | Optimal DP Solution
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
68.0K Views
High Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen