đ§© Beginner-Friendly Guide 'Largest Magic Square' â LeetCode 1895 (C++, Python, JavaScript)
Source: Dev.to
Problem Statement
Searching for patterns in a grid is a classic challenge in algorithmic thinking.
In this problem we are tasked with finding the largest possible subâgrid where every row, column, and both main diagonals add up to the exact same value.
Youâre given
- An
m Ă ninteger grid. - A Magic Square is a
k Ă ksubâgrid where the sum of every row, every column, and both diagonals are equal.
Your goal
Return the maximum side length k of any magic square hidden within the grid.
Examples
ExampleâŻ1

Input: grid = [[7,1,4,5,6],
[2,5,1,6,4],
[1,5,4,3,2],
[1,2,7,3,4]]
Output: 3
Explanation â The largest magic square has sizeâŻ3. Every row sum, column sum, and diagonal sum of this square equalsâŻ12.
- Row sums:
5+1+6 = 5+4+3 = 2+7+3 = 12 - Column sums:
5+5+2 = 1+4+7 = 6+3+3 = 12 - Diagonal sums:
5+4+3 = 6+4+2 = 12
ExampleâŻ2

Input: grid = [[5,1,3,1],
[9,3,3,1],
[1,3,3,8]]
Output: 2
Constraints
m == grid.lengthn == grid[i].length1 †m, n †501 †grid[i][j] †10â¶
Intuition
A bruteâforce solution would check every possible square of every size and manually sum its rows, columns, and diagonals. This repeats a lot of work.
To make it efficient we use prefix sums (running totals).
If we know the total of a row up to columnâŻ10 and up to columnâŻ5, the sum between 5 and 10 is just their difference.
We preâcompute four prefixâsum tables for every cell:
| Type | Meaning |
|---|---|
| Horizontal | Sum of elements in the current row up to this cell |
| Vertical | Sum of elements in the current column up to this cell |
| Main Diagonal | Sum along the topâleft â bottomâright diagonal up to this cell |
| AntiâDiagonal | Sum along the topâright â bottomâleft diagonal up to this cell |
With these tables, checking whether a k Ă k square is magic reduces to a few constantâtime subtractions.
We search from the largest possible side length min(m, n) downwards; the first size that satisfies the condition is the answer.
Solution Code
C++
class Solution {
public:
// Check whether the kĂk square with topâleft corner (r, c) is magic
bool isMagic(const vector>>& pref,
int r, int c, int k) {
// target sum = main diagonal of the square
int target = pref[r + k][c + k][2] - pref[r][c][2];
// antiâdiagonal must match
if (target != pref[r + k][c + 1][3] - pref[r][c + k + 1][3])
return false;
// each row sum must match
for (int i = r; i >& grid) {
int m = grid.size(), n = grid[0].size();
// pref[i][j] = {row, col, diag, antiâdiag} sums up to (iâ1, jâ1)
vector>> pref(m + 1,
vector>(n + 2, {0,0,0,0}));
for (int i = 1; i = 2; --k) {
for (int i = 0; i + k int:
m, n = len(grid), len(grid[0])
# pref[i][j] = [row, col, diag, anti_diag] sums up to (iâ1, jâ1)
# extra padding (n+2) simplifies antiâdiagonal indexing
pref = [[[0] * 4 for _ in range(n + 2)] for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
val = grid[i - 1][j - 1]
pref[i][j][0] = pref[i][j - 1][0] + val # row
pref[i][j][1] = pref[i - 1][j][1] + val # column
pref[i][j][2] = pref[i - 1][j - 1][2] + val # main diagonal
pref[i][j][3] = pref[i - 1][j + 1][3] + val # antiâdiagonal
# helper to test a kĂk square with topâleft corner (r, c)
def is_magic(r: int, c: int, k: int) -> bool:
target = pref[r + k][c + k][2] - pref[r][c][2] # main diagonal
if target != pref[r + k][c + 1][3] - pref[r][c + k + 1][3]:
return False
# rows
for i in range(r, r + k):
if pref[i + 1][c + k][0] - pref[i + 1][c][0] != target:
return False
# columns
for j in range(c, c + k):
if pref[r + k][j + 1][1] - pref[r][j + 1][1] != target:
return False
return True
for k in range(min(m, n), 1, -1):
for i in range(m - k + 1):
for j in range(n - k + 1):
if is_magic(i, j, k):
return k
return 1
Python
3] + val
def is_magic(r, c, k):
# Target sum from the main diagonal
target = pref[r + k][c + k][2] - pref[r][c][2]
# Check anti-diagonal
if target != pref[r + k][c + 1][3] - pref[r][c + k + 1][3]:
return False
# Check all rows
for i in range(r, r + k):
if pref[i + 1][c + k][0] - pref[i + 1][c][0] != target:
return False
# Check all columns
for j in range(c, c + k):
if pref[r + k][j + 1][1] - pref[r][j + 1][1] != target:
return False
return True
# Check from largest possible side length downwards
for k in range(min(m, n), 1, -1):
for i in range(m - k + 1):
for j in range(n - k + 1):
if is_magic(i, j, k):
return k
return 1
JavaScript
/**
* @param {number[][]} grid
* @return {number}
*/
var largestMagicSquare = function (grid) {
const m = grid.length;
const n = grid[0].length;
// Create prefix
How It Works â StepâbyâStep
- Build prefix tables â O(m·n) time, O(m·n) extra space.
- Iterate side lengths from large to small.
- For each possible topâleft corner, extract:
- main diagonal sum,
- antiâdiagonal sum,
- each row sum,
- each column sum
using only constantâtime subtractions of the prefix tables.
- The first size that passes all checks is the answer.
Because we stop at the first valid size, the overall complexity is
O(m·n·min(m, n)) in the worst case (still fast for m, n †50).