ExamAdda Logo

Maximal Square

Easy

Given an m x n binary matrix containing only '0' and '1', find the largest square containing only 1s.

Return the area of the largest such square.

Example 1

Input

m = 4
n = 5
matrix =
[
    [1, 0, 1, 0, 0],
    [1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [1, 0, 0, 1, 0]
]

Output

4

Explanation

The largest square containing only 1s has side length 2.

For example:

1 1
1 1

 

Its area is:

2 × 2 = 4

 

Therefore, the answer is 4.

Example 2

Input

m = 2
n = 2
matrix =
[
    [0, 1],
    [1, 0]
]

Output

1

Explanation

There is no 2 × 2 square containing only 1s.

Each individual 1 forms a square of side length 1.

Therefore, the maximum area is:

1 × 1 = 1

 

Constraints

1 <= m
n <= 300
matrix[i][j] is either '0' or '1'.
The matrix contains only binary values.
Return the area
not the side length
of the largest square.

Hints:

Hint 1

Let dp[i][j] represent the side length of the largest square of 1s whose bottom-right corner is at (i, j).

Hint 2

If the current cell is 1, look at three neighboring cells:

top
left
top-left

 

The recurrence is:

dp[i][j] = 1 + min(
   dp[i-1][j],
   dp[i][j-1],
   dp[i-1][j-1]
)

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 24, 2026

Last updated

Aug 24, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output