Largest Magic Square

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.

Example 1
7 1 4 5 6
2 5 1 6 4
1 5 4 3 2
1 2 7 3 4
Inputgrid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
Output3
The largest magic square has size 3, and every row sum, column sum, and diagonal sum of that square is equal to 12.
Example 2
5 1 3 1
9 3 3 1
1 3 3 8
Inputgrid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
Output2
The largest magic square found within the grid has side length 2.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • 1 <= grid[i][j] <= 10^6

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate