AlgoInsight

DSA problem

Maximal Square

Medium2D Grid DPPattern: 2D Grid DPtop600AmazonMicrosoftAppleGoogleAirbnb

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

A naive approach checks every possible square: pick a top-left corner, an edge length, and verify the whole square is all ones. That is O(m * n * min(m, n)^3) and far too slow for non-trivial grids. A better but still wasteful idea precomputes the 2-D prefix sum so each rectangle check is O(1), but you still enumerate O(m * n * min(m, n)) candidate squares.

The optimal technique is a beautiful 2-D DP. Define dp[i][j] as the side length of the largest all-ones square whose bottom-right corner is (i, j). If matrix[i][j] == 0, the cell cannot anchor any square so dp[i][j] = 0. Otherwise dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]). The intuition is that an all-ones square of side s ending here exists iff three smaller squares of side s - 1 ending at the three neighbors all exist; the limiting factor is the smallest of the three.

Tracking the running maximum of dp[i][j] gives the side length of the largest square; squaring it yields the area. The transition only needs the previous row plus one extra value (the old dp[i - 1][j - 1] that gets overwritten when dp[i][j - 1] is computed), so the DP compresses to a single 1-D array of length n with a single integer holding the diagonal predecessor. Total: O(m * n) time, O(n) space.

Examples

Example 1
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
Explanation: A 2x2 all-ones square sits in the middle-bottom of the grid, giving area 4.
Example 2
Input: matrix = [["0","1"],["1","0"]]
Output: 1
Explanation: No 2x2 all-ones square exists, but several single 1 cells give side 1 (area 1).
Example 3
Input: matrix = [["0"]]
Output: 0
Explanation: No 1 in the grid, so the largest all-ones square has area 0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingmatrix

Browse all DSA problems