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: 1
💡 Note: The 3x3 grid is not a magic square because the row sums are different: 7+1+4=12, 2+5+8=15, 6+9+3=18. Since the rows don't have equal sums, this cannot be a magic square. The largest magic square is 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
Largest Magic Square INPUT 3x3 Integer Grid 7 1 4 2 5 8 6 9 3 Input Values: grid = [[7,1,4], [2,5,8], [6,9,3]] ALGORITHM STEPS 1 Prefix Sums Compute row/col prefix sums for O(1) queries 2 Check All Squares For each k from max to 1, check all k x k subgrids 3 Validate Magic Row sums = Col sums = Diagonal sums 4 Return Max k First valid k found is the largest magic square Sum Verification: Row: 12, 15, 18 -- Col: 15, 15, 15 Diag: 15, 15 -- All = 15 [OK] FINAL RESULT 3x3 Magic Square Found! 7 1 4 2 5 8 6 9 3 OUTPUT 3 Magic Sum = 15 Key Insight: Use prefix sums for rows, columns, and diagonals to achieve O(1) sum queries. Check squares from largest to smallest size. The entire 3x3 grid forms a magic square with all rows, columns, and diagonals summing to 15. Time: O(m*n*min(m,n)^2) TutorialsPoint - Largest Magic Square | Optimal Solution with Prefix Sums
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