Magic Squares In Grid (LeetCode 840): Solution and Explanation

Medium
Array
Hash Table
Math
Matrix

Count the 3 x 3 contiguous subgrids of grid that are magic squares: they hold each of 1 to 9 exactly once and every row, column and both diagonals have the same sum.

Intuition

The grid is at most 10 x 10, so there are at most 64 windows of size 3 x 3. Checking every window directly is cheap, and the only question is how to check one window cleanly.

If a window holds 1 through 9, its three rows together sum to 45, so each row, and therefore every line, must sum to 15. The magic constant is fixed before you look at a single cell.

Add up the middle row, the middle column and the two diagonals. That is 4 lines, so the total is 60, and it counts the center four times and the other eight cells once each. So 60 = 45 + 3 * center, which forces the center to be 5. Any window whose center is not 5 can be skipped immediately.

For the windows that survive, check that the nine values are exactly 1..9 with no repeats, then that all eight lines sum to 15. The digit check matters: a window of nine 5s has every line summing to 15 but is not a magic square.

Approach: Slide a 3 x 3 window with a center filter

  1. Loop over every top-left corner (r, c) with r + 2 < rows and c + 2 < cols.
  2. If grid[r+1][c+1] != 5, skip the window.
  3. Read the nine values. Return false for the window if any value is outside 1..9 or repeats.
  4. Check the 3 rows, 3 columns and 2 diagonals. If every sum is 15, add one to the count.
  5. Return the count after the last window.

Step-by-step example

grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
  1. The grid is 3 x 4, so there are two windows: top-left corners (0,0) and (0,1).
  2. Window (0,0) has center 5. Its values are 4,3,8,9,5,1,2,7,6, which are 1..9 once each.
  3. Rows: 4+3+8, 9+5+1, 2+7+6 are all 15. Columns: 4+9+2, 3+5+7, 8+1+6 are all 15. Diagonals: 4+5+6 and 8+5+2 are 15. count = 1.
  4. Window (0,1) has center 1, not 5, so it is skipped.
  5. Return 1.

Code: Python, Java, C++

1class Solution:
2    def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
3        rows, cols = len(grid), len(grid[0])
4        count = 0
5        for r in range(rows - 2):
6            for c in range(cols - 2):
7                if grid[r + 1][c + 1] != 5:
8                    continue
9                if self.isMagic(grid, r, c):
10                    count += 1
11        return count
12
13    def isMagic(self, grid: List[List[int]], r: int, c: int) -> bool:
14        vals = [grid[r + i][c + j] for i in range(3) for j in range(3)]
15        if sorted(vals) != list(range(1, 10)):
16            return False
17        lines = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),
18                 (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
19        for a, b, d in lines:
20            if vals[a] + vals[b] + vals[d] != 15:
21                return False
22        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(row * col)

Each window does a constant amount of work: one center check, then at most 9 reads and 8 sums.

Space

O(1)

Only the nine values of the current window and a small seen table are stored.

Other approaches

Match against the 8 known squares (time O(row * col), space O(1))

There are exactly 8 magic squares of 1..9, the rotations and reflections of the Lo Shu square. Compare each window to that list, or check that its border, read clockwise, is a rotation of 8,1,6,7,2,9,4,3 or its reverse with 5 in the center.

Check every window without the center filter (time O(row * col), space O(1))

The same check without the early center == 5 test. It is still correct and still linear in the grid size, just slower by a constant factor.

Common mistakes

  • Checking only the line sums. A window of nine 5s has every line summing to 15 but does not hold 1..9.
  • Forgetting values above 9. The grid allows values up to 15, so a seen array of size 10 must be guarded with a range check first.
  • Off-by-one loop bounds. The last top-left corner is at row - 3 and col - 3, so grids smaller than 3 x 3 have no windows.
  • Checking only one diagonal. Both the main diagonal and the anti-diagonal must sum to 15.

Frequently asked questions

Why must the center be 5?

The middle row, middle column and both diagonals sum to 4 * 15 = 60. Together they cover every cell once except the center, which is covered four times, so 60 = 45 + 3 * center and the center is 5.

Why is the magic sum 15?

The numbers 1..9 add up to 45 and the three rows split them evenly, so each row, and therefore every line, sums to 45 / 3 = 15.

Is the distinct-digits check really needed if every line sums to 15?

Yes. The definition requires the distinct numbers 1 to 9, and grids of repeated 5s or values like 0 and 10 can satisfy all eight sums without being magic.