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 Square Detection ProcessInput Grid2764951943823×3 Magic SquareValidation Checks✓ Numbers 1-9 distinct✓ Row 1: 2+7+6 = 15✓ Row 2: 9+5+1 = 15✓ Row 3: 4+3+8 = 15✓ Col 1: 2+9+4 = 15✓ Col 2: 7+5+3 = 15✓ Col 3: 6+1+8 = 15✓ Diagonals: 15 & 15Magic Square Found!Count = 1Algorithm systematically checks each possible 3×3 position
Understanding the Visualization
1
Position Scanner
Move the 3×3 scanning window to each possible position in the grid
2
Number Validation
Check if the current 3×3 area contains numbers 1-9 exactly once
3
Sum Verification
Verify all rows, columns, and diagonals sum to the magic number 15
4
Count Magic Squares
Increment counter for each valid magic square found
Key Takeaway
🎯 Key Insight: Magic squares have fixed properties (numbers 1-9, sum=15) that make validation efficient with just basic checking!
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