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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code