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 Validation INPUT 2 0 0 1 0 3 1 0 0 5 2 0 4 0 0 2 Diagonal (X) Other X-Matrix Pattern: Diagonals != 0 All others == 0 n = 4 (4x4 matrix) grid[i][j] where 0 <= i,j < n ALGORITHM STEPS 1 Iterate matrix Loop i=0 to n-1, j=0 to n-1 2 Check diagonal If i==j or i+j==n-1 3 Validate value Diagonal: must be != 0 Non-diag: must be == 0 4 Early return Return false if violated Condition Checks: if (i==j || i+j==n-1): grid[i][j] != 0 ? OK else: grid[i][j] == 0 ? OK Violation --> return false FINAL RESULT 2 0 0 1 0 3 1 0 0 5 2 0 4 0 0 2 All Validations Passed! Diagonals: 2,1,3,1,5,2,4,2 All non-zero: OK Others: all zeros: OK Output: true Key Insight: For an n x n matrix, position (i, j) is on a diagonal if i == j (main diagonal) or i + j == n - 1 (anti-diagonal). Single pass O(n^2) validates all cells. Early return on first violation optimizes for invalid matrices. TutorialsPoint - Check if Matrix Is X-Matrix | Single Pass with Early Return
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