Count Three by Three Magic Squares Hidden in a Puzzle Grid
Last updated: November 29, 2026
Quick Overview
Given a grid of integers, count how many 3 x 3 contiguous subgrids are magic squares: they contain each number 1 to 9 exactly once and every row, column and both diagonals sum to 15.
0
0
0 solved
Given a grid of integers, count how many 3 x 3 contiguous subgrids are magic squares: they contain each number 1 to 9 exactly once and every row, column and both diagonals sum to 15.
A short Google online assessment style puzzle that rewards checking the definition carefully. Interviewers look at whether you verify distinctness and range, not just sums, and whether you spot that the center must be 5.
What the Interviewer Expects
- Iterates over all 3 x 3 windows
- Checks the values are exactly 1 through 9
- Checks all 3 rows, 3 columns and 2 diagonals sum to 15
- Uses the center-is-5 shortcut to prune
- Handles grids smaller than 3 x 3
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Generalize to k x k magic squares with any common sum.
- Prove the center of a 1..9 magic square is 5.
- Count windows where rows and columns match but diagonals are ignored.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
gridof ints (can include 0 or values above 9). - A window counts only if its nine values are exactly {1, ..., 9} and all eight lines sum to 15.
- Output: the number of qualifying windows....
High-Level Design
Slide the 3 x 3 window across every top-left position (r, c) with r <= m-3 and c <= n-3. For each, prune quickly if the center is not 5 (the four lines through the center sum to 60 = 3 * 15 + 3 ...