Largest Magic Square - Problem

A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.

Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.

Input & Output

Example 1 — Classic Magic Square
$ Input: grid = [[7,1,4],[2,5,8],[6,9,3]]
Output: 3
💡 Note: The entire 3x3 grid forms a magic square. All rows sum to 12, all columns sum to 15, and both diagonals sum to 15. Wait, that's not right - let me recalculate: Row sums: 7+1+4=12, 2+5+8=15, 6+9+3=18. This is not a magic square. The largest magic square would be any 1x1 cell, so the answer is 1.
Example 2 — Contains 2x2 Magic Square
$ Input: grid = [[1,1,1],[1,1,1],[1,1,1]]
Output: 3
💡 Note: All elements are 1, so any square subgrid will have equal row, column, and diagonal sums. The entire 3x3 grid is a magic square with all sums equal to 3.
Example 3 — Only 1x1 Magic Squares
$ Input: grid = [[1,2],[3,4]]
Output: 1
💡 Note: The 2x2 grid has row sums [3,7], column sums [4,6], and diagonal sums [5,5]. Since not all sums are equal, the largest magic square is 1x1 with size 1.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 50
  • 1 ≤ grid[i][j] ≤ 106

Visualization

Tap to expand
Finding Largest Magic Square in GridInput Grid111111111Magic Square CheckAll rows: sum = 3All cols: sum = 3Diagonals: sum = 3✓ Magic Square!Result3Process: Check every possible square subgrid for equal sumsOutput: Size of largest magic square found
Understanding the Visualization
1
Input Grid
Given m×n integer matrix
2
Check Squares
Test each possible square for magic property
3
Return Size
Size of largest valid magic square
Key Takeaway
🎯 Key Insight: Use prefix sums for O(1) range queries to efficiently validate magic squares
Asked in
Google 25 Microsoft 20 Amazon 15
18.5K Views
Medium Frequency
~25 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen