Problem Description
Given an n x n square matrix, determine if it is an X-Matrix. A matrix is an X-Matrix if:
- All the elements on both diagonals (primary and secondary) are non-zero.
- All other elements are zero. Return true if the matrix is an X-Matrix; otherwise, return false.
Key Insights
- Only the elements on the primary diagonal (where row index equals column index) and the secondary diagonal (where row index + column index equals n - 1) are allowed to be non-zero.
- Every other element in the matrix must be zero.
- The problem can be solved by iterating over all elements and checking conditions based on their indices.
Space and Time Complexity
Time Complexity: O(n^2) because each element in the matrix is visited exactly once. Space Complexity: O(1) as no extra space is used aside from a few variables.
Solution
The solution uses a simple iteration over the matrix. For each element at position (i, j):
- If the element is on either the primary diagonal (i == j) or the secondary diagonal (i + j == n - 1), verify that it is non-zero.
- Otherwise, check that the element is zero. If any condition is violated, return false immediately. If the entire matrix satisfies the X-Matrix criteria, return true.