> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Magic Squares In Grid Python Solution

> Tested Python solution for LeetCode 840 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 840, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Hash Table](/catalog/topics/hash-table), [Math](/catalog/topics/math), [Matrix](/catalog/topics/matrix). [View on LeetCode](https://leetcode.com/problems/magic-squares-in-grid/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 840   # by problem number
lcpy gen -s magic_squares_in_grid   # by problem name
```

## Problem

A `3 x 3` magic square is a `3 x 3` grid filled with **distinct** numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum.

Given a `row x col` `grid` of integers, how many `3 x 3` magic square subgrids are there?

**Note:** while a magic square can only contain numbers from `1` to `9`, `grid` may contain numbers up to `15`.

### Examples

```
Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
Explanation:
The following subgrid is a 3 x 3 magic square:

while this one is not:

In total, there is only one magic square inside the given grid.
```

```
Input: grid = [[8]]
Output: 0
```

### Constraints

* row == grid.length
* col == grid\[i].length
* 1 \<= row, col \<= 10
* 0 \<= grid\[i]\[j] \<= 15

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/magic_squares_in_grid/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/magic_squares_in_grid/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(rows * cols)
    # Space: O(1)
    def num_magic_squares_inside(self, grid: list[list[int]]) -> int:
        rows, cols = len(grid), len(grid[0])

        def is_magic(r: int, c: int) -> bool:
            # A 3x3 magic square over 1..9 always has center 5 and sum 15
            if grid[r + 1][c + 1] != 5:
                return False
            vals = [grid[r + i][c + j] for i in range(3) for j in range(3)]
            if sorted(vals) != list(range(1, 10)):
                return False
            if any(sum(grid[r + i][c : c + 3]) != 15 for i in range(3)):
                return False
            if any(sum(grid[r + i][c + j] for i in range(3)) != 15 for j in range(3)):
                return False
            return (
                grid[r][c] + grid[r + 1][c + 1] + grid[r + 2][c + 2] == 15
                and grid[r][c + 2] + grid[r + 1][c + 1] + grid[r + 2][c] == 15
            )

        return sum(is_magic(r, c) for r in range(rows - 2) for c in range(cols - 2))
```

## Complexity

| Time | Space |
| - | - |
| O(rows \* cols) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.