Magic Squares In Grid - Problem
Magic Squares in Grid

A 3×3 magic square is a fascinating mathematical construct where a 3×3 grid is filled with distinct numbers from 1 to 9 such that:
• Each row sums to the same value
• Each column sums to the same value
• Both diagonals sum to the same value

For example:
2 7 6
9 5 1
4 3 8


Each row, column, and diagonal sums to 15! 🎯

Given a row × col grid of integers, your task is to count how many 3×3 subgrids within this larger grid are valid magic squares. Note that while magic squares can only contain numbers 1-9, the input grid may contain numbers up to 15.

Input & Output

example_1.py — Basic Magic Square
$ Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
💡 Note: The 3×3 subgrid starting at position (0,0) contains numbers 1-9 exactly once, and all rows, columns, and diagonals sum to 15
example_2.py — No Magic Squares
$ Input: grid = [[8]]
Output: 0
💡 Note: The grid is too small to contain any 3×3 subgrids
example_3.py — Multiple Candidates
$ Input: grid = [[5,5,5],[5,5,5],[5,5,5]]
Output: 0
💡 Note: While all sums equal 15, the numbers are not distinct (all 5s), so this is not a valid magic square

Constraints

  • 1 ≤ grid.length, grid[i].length ≤ 10
  • 0 ≤ grid[i][j] ≤ 15
  • Magic squares must contain numbers 1-9 exactly once
  • All rows, columns, and diagonals must sum to 15

Visualization

Tap to expand
Magic Squares In Grid INPUT 3x4 Grid of Integers 4 3 8 4 9 5 1 9 2 7 6 2 3x3 Subgrid 1 3x3 Subgrid 2 Input Values grid = [ [4,3,8,4], [9,5,1,9], [2,7,6,2] ] ALGORITHM STEPS 1 Find All 3x3 Subgrids Iterate through positions (i,j) where i,j allow 3x3 2 Check Distinct 1-9 Verify all 9 cells contain unique values from 1 to 9 3 Validate Magic Sum Check rows, cols, diagonals all sum to 15 4 Count Valid Squares Increment count for each valid magic square found Magic Square Sum = 15 4 3 8 =15 9 5 1 =15 2 7 6 =15 15 15 15 Diag:15 Diag:15 FINAL RESULT Subgrids Analyzed: 2 Subgrid 1 (0,0) Valid Magic Square! Contains 1-9: OK All sums = 15: OK Count: +1 Subgrid 2 (0,1) Not a Magic Square Contains duplicates (4,4) Missing: 2,3 Count: +0 OUTPUT 1 Magic Square Count Key Insight: A 3x3 magic square always has center value 5 (quick filter). The magic constant is always 15 because (1+2+...+9)/3 = 45/3 = 15. There are only 8 valid magic square configurations (rotations and reflections of one base pattern), so we can also compare against known patterns. TutorialsPoint - Magic Squares In Grid | Optimal Solution
Asked in
Amazon 15 Microsoft 12 Google 8 Meta 5
24.0K Views
Medium Frequency
~15 min Avg. Time
890 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