Magic Squares In Grid

MediumMatrixsimulation

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A 3 x 3 *magic square* here means a 3 x 3 block that contains each integer from 1 to 9 exactly once, and in which all three rows, all three columns, and both diagonals have the same sum. Given an m x n integer matrix grid (values range from 0 to 15), count how many contiguous 3 x 3 subgrids are magic squares. Subgrids may overlap. Return that count as an integer (return 0 if the grid is smaller than 3 x 3).

Examples

Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]
Output: 1
The left 3x3 block uses 1..9 once and every row, column and diagonal sums to 15. The right block contains 4 twice.
Input: grid = [[8]]
Output: 0
The grid is too small to contain any 3x3 block.

Constraints

  • `1 <= m, n <= 10`
  • `0 <= grid[i][j] <= 15`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More simulation problems