Check if Matrix Is X-Matrix - Problem

A square matrix is said to be an X-Matrix if both of the following conditions hold:

  • All the elements in the diagonals of the matrix are non-zero.
  • All other elements are 0.

Given a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.

Input & Output

Example 1 — Valid X-Matrix
$ Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Output: true
💡 Note: All diagonal elements (2,3,1,2,4,1,2,2) are non-zero, and all non-diagonal elements are 0. This forms a valid X-Matrix pattern.
Example 2 — Invalid X-Matrix
$ Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
Output: false
💡 Note: Element at position (0,1) has value 7 which is non-zero, but it's not on any diagonal. Non-diagonal elements must be 0 in an X-Matrix.
Example 3 — Zero on Diagonal
$ Input: grid = [[5,0,5],[0,0,1],[5,1,5]]
Output: false
💡 Note: The center element at (1,1) is 0, but it's on the main diagonal. Diagonal elements must be non-zero in an X-Matrix.

Constraints

  • n == grid.length == grid[i].length
  • 3 ≤ n ≤ 100
  • -105 ≤ grid[i][j] ≤ 105

Visualization

Tap to expand
X-Matrix Pattern RecognitionInput Matrix:2001031005204002X-Pattern Analysis:✓ Green: Diagonal (must be non-zero)✓ Blue: Non-diagonal (must be zero)Result: true (Valid X-Matrix)
Understanding the Visualization
1
Input Matrix
4×4 matrix with values to be checked
2
Identify Diagonals
Main diagonal (i==j) and anti-diagonal (i+j==n-1)
3
Validate Pattern
Check if diagonals are non-zero and others are zero
Key Takeaway
🎯 Key Insight: Check diagonal positions using i==j (main) and i+j==n-1 (anti-diagonal) conditions
Asked in
Amazon 15 Microsoft 8
18.5K Views
Medium Frequency
~15 min Avg. Time
542 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen