Skip to content

Commit 3f57010

Browse files
chore: add LeetCode daily solution
1 parent 9e584b1 commit 3f57010

5 files changed

Lines changed: 127 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Magic Squares In Grid (Medium)
2+
3+
**Problem ID:** 840
4+
**Date:** 2025-12-30
5+
**Link:** https://leetcode.com/problems/magic-squares-in-grid/
6+
7+
## Approach
8+
9+
To solve the problem of counting 3x3 magic square subgrids in a given grid, we can follow a structured approach:
10+
11+
### Main Idea
12+
A 3x3 magic square must contain distinct integers from 1 to 9, and each row, column, and both diagonals must sum to the same value, which is 15 for a 3x3 magic square. Therefore, our goal is to identify all possible 3x3 subgrids within the given grid and check if they satisfy the conditions of a magic square.
13+
14+
### Steps to Solve the Problem
15+
1. **Iterate Through Possible Subgrids**: Since the grid can have dimensions up to 10x10, we can iterate through all possible top-left corners of 3x3 subgrids. The top-left corner can range from `(0, 0)` to `(row-3, col-3)`.
16+
17+
2. **Extract Subgrid**: For each position `(i, j)`, extract the 3x3 subgrid starting from that position. This involves collecting the elements in the range `grid[i][j]` to `grid[i+2][j+2]`.
18+
19+
3. **Check for Distinct Numbers**: Verify that all numbers in the extracted subgrid are distinct and fall within the range of 1 to 9. This can be efficiently done using a set to track the numbers.
20+
21+
4. **Calculate Sums**: If the numbers are valid, calculate the sums of each row, each column, and the two diagonals. All these sums should equal 15 for the subgrid to be a magic square.
22+
23+
5. **Count Valid Magic Squares**: Maintain a count of how many valid magic squares are found during the iteration.
24+
25+
### Data Structures
26+
- A set can be used to check for distinct numbers efficiently.
27+
- Simple integer variables can be used to store sums for rows, columns, and diagonals.
28+
29+
### Complexity
30+
- **Time Complexity**: The algorithm runs in O((row-2) * (col-2) * 1) = O(row * col) for iterating through subgrids and checking conditions, which is efficient given the constraints.
31+
- **Space Complexity**: The space complexity is O(1) for the counting variables and O(1) for the set used to check distinct numbers (since it can only hold up to 9 elements).
32+
33+
By following this approach, we can systematically determine the number of 3x3 magic squares in the given grid while adhering to the constraints and properties of magic squares.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public int numMagicSquaresInside(int[][] grid) {
3+
int count = 0;
4+
for (int i = 0; i < grid.length - 2; i++) {
5+
for (int j = 0; j < grid[0].length - 2; j++) {
6+
if (isMagicSquare(grid, i, j)) {
7+
count++;
8+
}
9+
}
10+
}
11+
return count;
12+
}
13+
14+
private boolean isMagicSquare(int[][] grid, int row, int col) {
15+
int[] nums = new int[10];
16+
for (int i = 0; i < 3; i++) {
17+
for (int j = 0; j < 3; j++) {
18+
nums[grid[row + i][col + j]]++;
19+
}
20+
}
21+
for (int i = 1; i <= 9; i++) {
22+
if (nums[i] != 1) return false;
23+
}
24+
return (grid[row][col] + grid[row][col + 1] + grid[row][col + 2] == 15) &&
25+
(grid[row + 1][col] + grid[row + 1][col + 1] + grid[row + 1][col + 2] == 15) &&
26+
(grid[row + 2][col] + grid[row + 2][col + 1] + grid[row + 2][col + 2] == 15) &&
27+
(grid[row][col] + grid[row + 1][col] + grid[row + 2][col] == 15) &&
28+
(grid[row][col + 1] + grid[row + 1][col + 1] + grid[row + 2][col + 1] == 15) &&
29+
(grid[row][col + 2] + grid[row + 1][col + 2] + grid[row + 2][col + 2] == 15) &&
30+
(grid[row][col] + grid[row + 1][col + 1] + grid[row + 2][col + 2] == 15) &&
31+
(grid[row + 2][col] + grid[row + 1][col + 1] + grid[row][col + 2] == 15);
32+
}
33+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
var numMagicSquaresInside = function(grid) {
2+
const isMagicSquare = (square) => {
3+
const nums = new Set();
4+
let sum = 0;
5+
for (let i = 0; i < 3; i++) {
6+
sum += square[i][0];
7+
nums.add(square[i][0]);
8+
nums.add(square[i][1]);
9+
nums.add(square[i][2]);
10+
}
11+
for (let j = 0; j < 3; j++) {
12+
let colSum = square[0][j] + square[1][j] + square[2][j];
13+
if (colSum !== sum) return false;
14+
}
15+
const diag1 = square[0][0] + square[1][1] + square[2][2];
16+
const diag2 = square[0][2] + square[1][1] + square[2][0];
17+
if (diag1 !== sum || diag2 !== sum) return false;
18+
return nums.size === 9 && [...nums].every(num => num >= 1 && num <= 9);
19+
};
20+
21+
let count = 0;
22+
const rows = grid.length;
23+
const cols = grid[0].length;
24+
25+
for (let i = 0; i <= rows - 3; i++) {
26+
for (let j = 0; j <= cols - 3; j++) {
27+
const square = [
28+
[grid[i][j], grid[i][j + 1], grid[i][j + 2]],
29+
[grid[i + 1][j], grid[i + 1][j + 1], grid[i + 1][j + 2]],
30+
[grid[i + 2][j], grid[i + 2][j + 1], grid[i + 2][j + 2]]
31+
];
32+
if (isMagicSquare(square)) {
33+
count++;
34+
}
35+
}
36+
}
37+
return count;
38+
};
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution:
2+
def numMagicSquaresInside(self, grid: List[List[int]]) -> int:
3+
def isMagicSquare(x, y):
4+
nums = {grid[x+i][y+j] for i in range(3) for j in range(3)}
5+
if nums != {1, 2, 3, 4, 5, 6, 7, 8, 9}:
6+
return False
7+
return (grid[x][y] + grid[x][y+1] + grid[x][y+2] ==
8+
grid[x+1][y] + grid[x+1][y+1] + grid[x+1][y+2] ==
9+
grid[x+2][y] + grid[x+2][y+1] + grid[x+2][y+2] ==
10+
grid[x][y] + grid[x+1][y] + grid[x+2][y] ==
11+
grid[x][y+1] + grid[x+1][y+1] + grid[x+2][y+1] ==
12+
grid[x][y+2] + grid[x+1][y+2] + grid[x+2][y+2] ==
13+
grid[x][y] + grid[x+1][y+1] + grid[x+2][y+2] ==
14+
grid[x+2][y] + grid[x+1][y+1] + grid[x][y+2])
15+
16+
count = 0
17+
rows, cols = len(grid), len(grid[0])
18+
for i in range(rows - 2):
19+
for j in range(cols - 2):
20+
if isMagicSquare(i, j):
21+
count += 1
22+
return count

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,3 +320,4 @@ Through completing the Blind 75 and NeetCode 150, you will have mastered:
320320
- 2025-12-27 — [Meeting Rooms III](https://leetcode.com/problems/meeting-rooms-iii/) (Hard) → `Hard/2025-12-27-2402-Meeting-Rooms-III`
321321
- 2025-12-28 — [Count Negative Numbers in a Sorted Matrix](https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/) (Easy) → `Easy/2025-12-28-1351-Count-Negative-Numbers-in-a-Sorted-Matrix`
322322
- 2025-12-29 — [Pyramid Transition Matrix](https://leetcode.com/problems/pyramid-transition-matrix/) (Medium) → `Medium/2025-12-29-756-Pyramid-Transition-Matrix`
323+
- 2025-12-30 — [Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid/) (Medium) → `Medium/2025-12-30-840-Magic-Squares-In-Grid`

0 commit comments

Comments
 (0)