Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
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 a size of 3. Every row sum, column sum, and diagonal sum of this magic square is equal to 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] <= 106Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
[[5,1,3,1],[9,3,3,1],[1,3,3,8]]
magic-squares-in-grid)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1895: Largest Magic Square
class Solution {
private int[][] rowsum;
private int[][] colsum;
public int largestMagicSquare(int[][] grid) {
int m = grid.length, n = grid[0].length;
rowsum = new int[m + 1][n + 1];
colsum = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
rowsum[i][j] = rowsum[i][j - 1] + grid[i - 1][j - 1];
colsum[i][j] = colsum[i - 1][j] + grid[i - 1][j - 1];
}
}
for (int k = Math.min(m, n); k > 1; --k) {
for (int i = 0; i + k - 1 < m; ++i) {
for (int j = 0; j + k - 1 < n; ++j) {
int i2 = i + k - 1, j2 = j + k - 1;
if (check(grid, i, j, i2, j2)) {
return k;
}
}
}
}
return 1;
}
private boolean check(int[][] grid, int x1, int y1, int x2, int y2) {
int val = rowsum[x1 + 1][y2 + 1] - rowsum[x1 + 1][y1];
for (int i = x1 + 1; i <= x2; ++i) {
if (rowsum[i + 1][y2 + 1] - rowsum[i + 1][y1] != val) {
return false;
}
}
for (int j = y1; j <= y2; ++j) {
if (colsum[x2 + 1][j + 1] - colsum[x1][j + 1] != val) {
return false;
}
}
int s = 0;
for (int i = x1, j = y1; i <= x2; ++i, ++j) {
s += grid[i][j];
}
if (s != val) {
return false;
}
s = 0;
for (int i = x1, j = y2; i <= x2; ++i, --j) {
s += grid[i][j];
}
if (s != val) {
return false;
}
return true;
}
}
// Accepted solution for LeetCode #1895: Largest Magic Square
func largestMagicSquare(grid [][]int) int {
m, n := len(grid), len(grid[0])
rowsum := make([][]int, m+1)
colsum := make([][]int, m+1)
for i := 0; i <= m; i++ {
rowsum[i] = make([]int, n+1)
colsum[i] = make([]int, n+1)
}
for i := 1; i < m+1; i++ {
for j := 1; j < n+1; j++ {
rowsum[i][j] = rowsum[i][j-1] + grid[i-1][j-1]
colsum[i][j] = colsum[i-1][j] + grid[i-1][j-1]
}
}
for k := min(m, n); k > 1; k-- {
for i := 0; i+k-1 < m; i++ {
for j := 0; j+k-1 < n; j++ {
i2, j2 := i+k-1, j+k-1
if check(grid, rowsum, colsum, i, j, i2, j2) {
return k
}
}
}
}
return 1
}
func check(grid, rowsum, colsum [][]int, x1, y1, x2, y2 int) bool {
val := rowsum[x1+1][y2+1] - rowsum[x1+1][y1]
for i := x1 + 1; i < x2+1; i++ {
if rowsum[i+1][y2+1]-rowsum[i+1][y1] != val {
return false
}
}
for j := y1; j < y2+1; j++ {
if colsum[x2+1][j+1]-colsum[x1][j+1] != val {
return false
}
}
s := 0
for i, j := x1, y1; i <= x2; i, j = i+1, j+1 {
s += grid[i][j]
}
if s != val {
return false
}
s = 0
for i, j := x1, y2; i <= x2; i, j = i+1, j-1 {
s += grid[i][j]
}
if s != val {
return false
}
return true
}
# Accepted solution for LeetCode #1895: Largest Magic Square
class Solution:
def largestMagicSquare(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
rowsum = [[0] * (n + 1) for _ in range(m + 1)]
colsum = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
rowsum[i][j] = rowsum[i][j - 1] + grid[i - 1][j - 1]
colsum[i][j] = colsum[i - 1][j] + grid[i - 1][j - 1]
def check(x1, y1, x2, y2):
val = rowsum[x1 + 1][y2 + 1] - rowsum[x1 + 1][y1]
for i in range(x1 + 1, x2 + 1):
if rowsum[i + 1][y2 + 1] - rowsum[i + 1][y1] != val:
return False
for j in range(y1, y2 + 1):
if colsum[x2 + 1][j + 1] - colsum[x1][j + 1] != val:
return False
s, i, j = 0, x1, y1
while i <= x2:
s += grid[i][j]
i += 1
j += 1
if s != val:
return False
s, i, j = 0, x1, y2
while i <= x2:
s += grid[i][j]
i += 1
j -= 1
if s != val:
return False
return True
for k in range(min(m, n), 1, -1):
i = 0
while i + k - 1 < m:
j = 0
while j + k - 1 < n:
i2, j2 = i + k - 1, j + k - 1
if check(i, j, i2, j2):
return k
j += 1
i += 1
return 1
// Accepted solution for LeetCode #1895: Largest Magic Square
/**
* [1895] 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg" style="width: 413px; height: 335px;" />
* 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 a size of 3.
* Every row sum, column sum, and diagonal sum of this magic square is equal to 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg" style="width: 333px; height: 255px;" />
* Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]
* Output: 2
*
*
* Constraints:
*
* m == grid.length
* n == grid[i].length
* 1 <= m, n <= 50
* 1 <= grid[i][j] <= 10^6
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/largest-magic-square/
// discuss: https://leetcode.com/problems/largest-magic-square/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn largest_magic_square(grid: Vec<Vec<i32>>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1895_example_1() {
let grid = vec![
vec![7, 1, 4, 5, 6],
vec![2, 5, 1, 6, 4],
vec![1, 5, 4, 3, 2],
vec![1, 2, 7, 3, 4],
];
let result = 3;
assert_eq!(Solution::largest_magic_square(grid), result);
}
#[test]
#[ignore]
fn test_1895_example_2() {
let grid = vec![vec![5, 1, 3, 1], vec![9, 3, 3, 1], vec![1, 3, 3, 8]];
let result = 2;
assert_eq!(Solution::largest_magic_square(grid), result);
}
}
// Accepted solution for LeetCode #1895: Largest Magic Square
function largestMagicSquare(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
const rowsum: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
const colsum: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
rowsum[i][j] = rowsum[i][j - 1] + grid[i - 1][j - 1];
colsum[i][j] = colsum[i - 1][j] + grid[i - 1][j - 1];
}
}
const check = (x1: number, y1: number, x2: number, y2: number): boolean => {
const val = rowsum[x1 + 1][y2 + 1] - rowsum[x1 + 1][y1];
for (let i = x1 + 1; i <= x2; ++i) {
if (rowsum[i + 1][y2 + 1] - rowsum[i + 1][y1] !== val) {
return false;
}
}
for (let j = y1; j <= y2; ++j) {
if (colsum[x2 + 1][j + 1] - colsum[x1][j + 1] !== val) {
return false;
}
}
let s = 0;
for (let i = x1, j = y1; i <= x2; ++i, ++j) {
s += grid[i][j];
}
if (s !== val) {
return false;
}
s = 0;
for (let i = x1, j = y2; i <= x2; ++i, --j) {
s += grid[i][j];
}
if (s !== val) {
return false;
}
return true;
};
for (let k = Math.min(m, n); k > 1; --k) {
for (let i = 0; i + k - 1 < m; ++i) {
for (let j = 0; j + k - 1 < n; ++j) {
const i2 = i + k - 1,
j2 = j + k - 1;
if (check(i, j, i2, j2)) {
return k;
}
}
}
}
return 1;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.