Maximal Square — LeetCode 221 Python Solution

MediumArrayDynamic ProgrammingMatrix
Problem
#221
Reading time
2 min

The problem

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

Example

Input
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output
4

Python solution

Python
class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        m, n = len(matrix), len(matrix[0])
        dp = [[0] * (n + 1) for _ in range(m + 1)]
        mx = 0
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == '1':
                    dp[i + 1][j + 1] = min(dp[i][j + 1], dp[i + 1][j], dp[i][j]) + 1
                    mx = max(mx, dp[i + 1][j + 1])
        return mx * mx

Complexity

MeasureComplexity
TimeO(m\times n)
SpaceO(m\times n) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 221. Maximal Square is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 221. Maximal Square?
LeetCode 221. Maximal Square is rated Medium on LeetCode.
What is the time complexity of LeetCode 221. Maximal Square?
The Python solution on this page runs in O(m\times n).
What is the space complexity of LeetCode 221. Maximal Square?
The Python solution on this page uses O(m\times n) auxiliary space.
What topics does LeetCode 221. Maximal Square cover?
LeetCode 221. Maximal Square is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview