Leetcode #2319: Check if Matrix Is X-Matrix
In this guide, we solve Leetcode #2319 Check if Matrix Is X-Matrix in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: No
- Tags: Array, Matrix
Intuition
Grid problems are easiest when you define clear row/column boundaries.
A consistent traversal order prevents off-by-one errors.
Approach
Iterate by rows, columns, or layers depending on the requirement.
Keep bounds updated as the traversal progresses.
Steps:
- Define bounds or directions.
- Visit cells in order.
- Update result and move bounds.
Example
Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
Output: true
Explanation: Refer to the diagram above.
An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.
Thus, grid is an X-Matrix.
Python Solution
class Solution:
def checkXMatrix(self, grid: List[List[int]]) -> bool:
for i, row in enumerate(grid):
for j, v in enumerate(row):
if i == j or i + j == len(grid) - 1:
if v == 0:
return False
elif v:
return False
return True
Complexity
The time complexity is , where is the number of rows or columns of the matrix. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.