The Magic Squares In Grid interview question gives you a grid of integers. Your goal is to count how many contiguous subgrids constitute a "magic square". A magic square is a grid filled with distinct numbers from exactly 1 to 9, where every row, every column, and both diagonals all sum up to the exact same number (which happens to be 15).
This is a matrix parsing and validation problem. Interviewers ask it to test your attention to detail and your ability to write clean, modular validation functions. It evaluates whether you can handle dense lists of constraints (distinct 1-9, specific dimension, multiple sum checks) without writing a massive, unreadable block of spaghetti code.
This utilizes the Sliding Window / Subgrid Search pattern combined with Math / Validation Helper Functions. Since the size of the magic square is fixed at , you simply iterate through all possible top-left corners of a grid within the larger matrix. For each possible subgrid, you pass it to a helper function that rigorously checks the 1-9 distinct property and the row/col/diagonal sums.
If you are given a grid, you iterate row from 0 to rows - 3 and col from 0 to cols - 3.
For a specific subgrid at (row, col):
5. You can use if (grid[row+1][col+1] != 5) return false; as an instant filter before doing the heavy sum calculations!The most prevalent mistake is forgetting to verify that the numbers are strictly between 1 and 9 and are completely distinct. If a grid contains 5 in every single cell, the rows and columns will all sum to 15, but it is NOT a valid magic square. Candidates often only check the sums and fail the test cases containing duplicate numbers or numbers like 0 or 10.
When tackling the Magic Squares In Grid coding problem, isolate the validation logic. Do not write the sum checks inside your main double-for loop. Create a private boolean isMagicSquare(grid, r, c) method. Mentioning the "center must be 5" trick to the interviewer will earn you massive bonus points, as it shows strong analytical and mathematical deduction skills alongside your coding ability.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Missing and Repeated Values | Easy | Solve | |
| Flip Columns For Maximum Number of Equal Rows | Medium | Solve | |
| Lonely Pixel I | Medium | Solve | |
| Lonely Pixel II | Medium | Solve | |
| Number of Boomerangs | Medium | Solve |