Check if Matrix Is X-Matrix — LeetCode 2319 Python Solution

EasyArrayMatrix
Problem
#2319
Reading time
2 min

The 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.

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.

Python solution

Python
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

MeasureComplexity
TimeO(n^2), where n is the number of rows or columns of the matrix
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2319. Check if Matrix Is X-Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2319. Check if Matrix Is X-Matrix?
LeetCode 2319. Check if Matrix Is X-Matrix is rated Easy on LeetCode.
What topics does LeetCode 2319. Check if Matrix Is X-Matrix cover?
LeetCode 2319. Check if Matrix Is X-Matrix is tagged Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview