</>

221. Maximal Square

Medium
2-D Dynamic Programming Time O(M*N) Space O(M*N)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
2-D Dynamic Programming
Time
O(M*N)
Space
O(M*N)

Standard Solution (C++)

SummaryGiven a 2-D grid of '0' and '1' characters, find the side length of the largest axis-aligned square containing only '1's and return its area.

Approach
  • Define dp[j] as the side length of the largest all-'1' square whose bottom-right corner sits at the current row, column j.
  • The classic recurrence is dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 when matrix[i][j] == '1': the three neighbors cap how far the square can extend up, left, and diagonally.
  • Compress to a single 1-D array by iterating row by row, keeping one extra variable diag to hold the value that will be overwritten (the true dp[i-1][j-1]).
  • Track the running maximum side length and return its square as the area.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m = matrix.size(), n = matrix[0].size();
        // dp[j] = side length of the largest square ending at (current row, j)
        vector<int> dp(n + 1, 0);
        int maxSide = 0;

        for (int i = 1; i <= m; ++i) {
            int diag = 0;               // holds dp[i-1][j-1] before it is overwritten
            for (int j = 1; j <= n; ++j) {
                int prev = dp[j];       // save dp[i-1][j] before update
                if (matrix[i - 1][j - 1] == '1') {
                    // min of: above (dp[j]), left (dp[j-1]), diagonal (diag)
                    dp[j] = min({dp[j], dp[j - 1], diag}) + 1;
                    maxSide = max(maxSide, dp[j]);
                } else {
                    dp[j] = 0;
                }
                diag = prev;            // next iteration's diagonal is this cell's old value
            }
        }

        return maxSide * maxSide;
    }
};
Time O(m * n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m=matrix.size();
        int n=matrix[0].size();
        int maxEdge=0;
        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));

        for(int i=1; i<m+1; ++i){
            for(int j=1; j<n+1; ++j){
                if(matrix[i-1][j-1]=='1'){
                    dp[i][j]=min({dp[i-1][j-1], dp[i-1][j], dp[i][j-1]})+1;
                    maxEdge=max(maxEdge, dp[i][j]);
                }
            }
        }

        return maxEdge*maxEdge;
    }
};

// Time Complexity: O(M*N), where M is the number of rows and N is the number of columns in the matrix.
// Space Complexity: O(M*N) for the dp array.
// The space can be optimized to O(N) by using only two rows, but here we use O(M*N) for clarity.
// The result is the area of the largest square found, which is maxEdge squared.
Time O(M*N) Space O(M*N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern