Largest Magic Square - Problem
A magic square is like a perfect puzzle where all the numbers align harmoniously! ๐ฏ
Given a k ร k grid filled with integers, it becomes a magic square when:
- Every row sum equals the same value
- Every column sum equals the same value
- Both diagonal sums equal the same value
Note: The integers don't need to be distinct, and every 1ร1 grid is trivially a magic square.
Your Mission: Given an m ร n integer grid, find the size (side length k) of the largest magic square that can be found within this grid.
Example: In a 4ร4 grid, you might find a 3ร3 magic square where all rows, columns, and diagonals sum to 15.
Input & Output
example_1.py โ Basic Magic Square
$
Input:
grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
โบ
Output:
2
๐ก Note:
The largest magic square is 2ร2. For example, the subgrid [[7,1],[2,5]] has sums: rows=[8,7], cols=[9,6], diags=[12,3] - not magic. But [[1,6],[3,2]] has sums: rows=[7,5], cols=[4,8], diags=[3,8] - not magic either. However, [[5,1],[5,4]] has all sums equal to 6: rows=[6,9], cols=[10,5], diags=[9,6] - still not magic. The actual 2ร2 magic square would be found through systematic checking.
example_2.py โ Single Element
$
Input:
grid = [[5]]
โบ
Output:
1
๐ก Note:
A 1ร1 grid is trivially a magic square since there's only one element, so all 'sums' are equal to that element's value.
example_3.py โ Large Grid
$
Input:
grid = [[3,2,9,2,7],[6,1,8,4,2],[7,5,3,2,7],[2,9,4,9,6],[4,3,8,2,5]]
โบ
Output:
1
๐ก Note:
In this 5ร5 grid, no magic square larger than 1ร1 can be found. Every 2ร2, 3ร3, 4ร4, and 5ร5 subgrid fails the magic square test where all rows, columns, and diagonals must have equal sums.
Constraints
- m == grid.length
- n == grid[i].length
- 1 โค m, n โค 50
- 1 โค grid[i][j] โค 106
- Time limit: 2 seconds
Visualization
Tap to expand
Understanding the Visualization
1
Scan Grid Positions
Try every possible top-left corner position for potential magic squares
2
Test Square Sizes
For each position, test increasing square sizes from 1ร1 to maximum possible
3
Verify Magic Property
Check if all rows, columns, and diagonals sum to the same value
4
Track Maximum
Keep track of the largest valid magic square size found
5
Optimize with Prefix Sums
Use precomputed sums to avoid recalculating the same regions repeatedly
Key Takeaway
๐ฏ Key Insight: Use prefix sums to transform O(kยฒ) sum calculations into O(1) lookups, then binary search on the answer since magic square existence has monotonic property.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code