15% off all plans & roadmaps Use code
See plansLeetCode 221 · Solution & editorial
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.
Maximal Square is a Dynamic Programming (DP) Patterns problem, in the 2D Array (Unique Paths on Grid) subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
Count paths and find optimal paths in grids using 2D dynamic programming.
The reference solution runs in O(m * n) time and O(m * n) space.
Maximal Square has been reported in interviews at Amazon, IBM, Google, Twitter, ByteDance, Apple.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Maximal Square is a Dynamic Programming (DP) Patterns problem, in the 2D Array (Unique Paths on Grid) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.