Check if Matrix Is X-Matrix - Problem

๐ŸŽฏ Check if Matrix Forms an X Pattern

Imagine you're looking at a square grid from above - can you spot an X pattern? An X-Matrix is a special type of square matrix that follows two simple rules:

  • ๐Ÿ“ All elements on both diagonals (main diagonal and anti-diagonal) must be non-zero
  • ๐Ÿšซ All other elements must be exactly zero

Given a 2D integer array grid of size n x n, your task is to determine whether it forms a valid X-Matrix. Return true if it does, false otherwise.

Example: In a 3x3 matrix, positions (0,0), (0,2), (1,1), (2,0), and (2,2) should be non-zero, while positions (0,1), (1,0), (1,2), and (2,1) must be zero.

Input & Output

example_1.py โ€” Valid X-Matrix
$ Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
โ€บ Output: true
๐Ÿ’ก Note: This is a valid X-Matrix because all diagonal elements (2,1,3,2,5,4,2) are non-zero and all non-diagonal elements are zero.
example_2.py โ€” Invalid X-Matrix
$ Input: grid = [[5,7,0],[0,3,1],[0,5,0]]
โ€บ Output: false
๐Ÿ’ก Note: This is not an X-Matrix because grid[0][1] = 7 and grid[1][2] = 1 are non-diagonal elements that should be zero.
example_3.py โ€” Single Element Matrix
$ Input: grid = [[5]]
โ€บ Output: true
๐Ÿ’ก Note: A 1ร—1 matrix is always an X-Matrix if the single element (which is on both diagonals) is non-zero.

Constraints

  • n == grid.length == grid[i].length
  • 3 โ‰ค n โ‰ค 100
  • -105 โ‰ค grid[i][j] โ‰ค 105
  • The matrix is guaranteed to be square

Visualization

Tap to expand
X-Matrix Validation Visualizationโœ“ Valid X-Matrix2001031005204002โœ— Invalid X-Matrix570031050Diagonal: Non-zero (correct)Non-diagonal: Zero (correct)Rule violation (incorrect)
Understanding the Visualization
1
Identify Diagonal Positions
Locate all positions that form the X pattern (main diagonal i==j and anti-diagonal i+j==n-1)
2
Validate Diagonal Elements
Ensure all diagonal positions contain non-zero values
3
Validate Non-Diagonal Elements
Ensure all other positions contain exactly zero
4
Final Verdict
Return true if all conditions met, false otherwise
Key Takeaway
๐ŸŽฏ Key Insight: An X-Matrix has a simple pattern - diagonal positions (i==j or i+j==n-1) must be non-zero, all others must be zero. This can be validated in a single O(nยฒ) pass through the matrix.
Asked in
Amazon 15 Microsoft 12 Google 8 Meta 6
28.4K Views
Medium Frequency
~8 min Avg. Time
842 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