LeetCode 221: Maximal Square Solution
Master LeetCode problem 221 (Maximal Square), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
221. Maximal Square
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming. We will create a 2D array dp where dp[i][j] will represent the size of the largest square ending at position (i, j). We will iterate over the matrix, updating dp[i][j] based on the values of the neighboring cells. The maximum value in the dp array will give us the side length of the largest square, and its area will be the square of this side length.
Here are the steps:
- Initialize a 2D array
dpof sizem x nwheredp[i][j]will store the side length of the largest square ending at position(i, j). - Initialize the first row and first column of
dpwith values from the input matrix as they are. - For each cell
(i, j)in the matrix starting from(1, 1), if the current cell is '1':- Update
dp[i][j]asmin(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1because we can extend the square only if all three neighbors are also part of a square.
- Update
- Finally, return the maximum value in the
dparray squared as the area of the largest square.
The time complexity of this solution is O(mn) where m and n are the dimensions of the input matrix. The space complexity is also O(mn) for the dp array.
Solution Code
class Solution {
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] dp = new int[m][n];
int maxSide = 0;
for (int i = 0; i < m; i++) {
dp[i][0] = matrix[i][0] - '0';
maxSide = Math.max(maxSide, dp[i][0]);
}
for (int j = 0; j < n; j++) {
dp[0][j] = matrix[0][j] - '0';
maxSide = Math.max(maxSide, dp[0][j]);
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
maxSide = Math.max(maxSide, dp[i][j]);
}
}
}
return maxSide * maxSide;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 221 (Maximal Square)?
This page provides optimized solutions for LeetCode problem 221 (Maximal Square) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 221 (Maximal Square)?
The time complexity for LeetCode 221 (Maximal Square) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 221 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 221 in Java, C++, or Python.