LeetCode 1895: Largest Magic Square Solution
Master LeetCode problem 1895 (Largest Magic 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.
1895. Largest Magic Square
Problem Explanation
Explanation
To find the largest magic square within the given grid, we can iterate over each cell in the grid and check if it can be the top-left corner of a magic square of some size. We start with the largest possible size k and iteratively reduce k until we find a valid magic square.
For each cell, we check if it's possible to form a magic square of size k with that cell as the top-left corner. To do this, we need to check the row sums, column sums, and diagonal sums of the k x k square starting from that cell.
The time complexity of this approach is O(m * n * min(m, n)^2) where m and n are the dimensions of the grid. The space complexity is O(1).
Solution Code
class Solution {
public int largestMagicSquare(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int maxSize = Math.min(m, n);
for (int k = maxSize; k >= 1; k--) {
for (int i = 0; i <= m - k; i++) {
for (int j = 0; j <= n - k; j++) {
if (isMagicSquare(grid, i, j, k)) {
return k;
}
}
}
}
return 1;
}
private boolean isMagicSquare(int[][] grid, int row, int col, int k) {
int sum = 0;
int sumDiag1 = 0;
int sumDiag2 = 0;
for (int i = 0; i < k; i++) {
int rowSum = 0;
int colSum = 0;
sumDiag1 += grid[row + i][col + i];
sumDiag2 += grid[row + i][col + k - 1 - i];
for (int j = 0; j < k; j++) {
rowSum += grid[row + i][col + j];
colSum += grid[row + j][col + i];
}
if (i == 0) {
sum = rowSum;
}
if (rowSum != sum || colSum != sum) {
return false;
}
}
return sum == sumDiag1 && sum == sumDiag2;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1895 (Largest Magic Square)?
This page provides optimized solutions for LeetCode problem 1895 (Largest Magic 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 1895 (Largest Magic Square)?
The time complexity for LeetCode 1895 (Largest Magic Square) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1895 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1895 in Java, C++, or Python.