Check if Matrix Is X-Matrix
What is this problem about?
The "Check if Matrix Is X-Matrix interview question" is a matrix validation task. An nimesn square matrix is an "X-Matrix" if:
- Every element on the two main diagonals is non-zero.
- Every other element (those NOT on the diagonals) is exactly zero.
The two main diagonals are the primary diagonal (top-left to bottom-right) and the anti-diagonal (top-right to bottom-left).
Why is this asked in interviews?
Companies like Google and Amazon use the "Check if Matrix Is X-Matrix coding problem" to assess a candidate's comfort with 2D array indexing. It’s a foundational "Matrix interview pattern" exercise that requires identifying specific cells based on their (row,col) coordinates.
Algorithmic pattern used
This problem follows the Coordinate Geometry in Matrices pattern.
For a square matrix of size n:
- A cell (i,j) is on the primary diagonal if
i == j.
- A cell (i,j) is on the anti-diagonal if
i + j == n - 1.
- Loop: Iterate through every cell (i,j) in the matrix.
- Conditional Check:
- If
i == j or i + j == n - 1: The value must be non-zero.
- Else: The value must be zero.
- Failure: Return false as soon as a condition is violated.
Example explanation
Matrix 3imes3:
2 0 2
0 5 0
2 0 2
- (0,0): i=j. Val 2 (!= 0). OK.
- (0,1): Not diagonal. Val 0. OK.
- (0,2): i+j=2. Val 2 (!= 0). OK.
- (1,1): i=j and i+j=2. Val 5 (!= 0). OK.
Result: True.
Common mistakes candidates make
- Diagonal Logic: Miscalculating the anti-diagonal condition (using
i + j == n instead of n - 1).
- Incorrect Bounds: Hardcoding the matrix size instead of using
length.
- Logic Flip: Confusing the requirements (e.g., checking if non-diagonals are non-zero).
Interview preparation tip
Practice identifying "special" indices in matrices. The primary and anti-diagonals are the most common, but also know how to identify the "middle row" or "outer boundary." This is a core "Array interview pattern" for grid problems.