← Back to index
MediumTypeScript3 min read

Magic Squares in Grid

Check every 3×3 window for the 1..9 magic square pattern using center and parity pruning.

gridbrute-forcehashing

Problem link

View on LeetCode

Solutions in this repo

  • TypeScript../magic-squares-in-grid/solution.tsTypeScript solution

Magic squares of size 3 have a strict structure: the center must be 5, each row, column, and diagonal sums to 15, and the digits 1 through 9 appear exactly once. I iterate each 3×3 sub-grid and apply those checks in order of cheapest to most expensive.

The early rejection on the center cell eliminates about 80% of windows up front. A simple frequency map handles the uniqueness constraint before I bother computing row or column sums.

Checklist

  • Center cell is 5.
  • All values are between 1 and 9 inclusive.
  • Each value appears exactly once.
  • Every row, column, and diagonal totals 15 (precomputed row sums make this quick).

Complexity

For an m×n grid there are (m - 2)(n - 2) windows. Each validation is constant work on nine cells, so the whole algorithm is O(mn) time and O(1) additional space.