#2319

Check if Matrix Is X-Matrix

Easy
ArrayMatrixArrayMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution leverages the same checks but is structured to minimize unnecessary checks by directly focusing on the diagonal and non-diagonal elements in a single pass.

⚙️

Algorithm

4 steps
  1. 1Step 1: Loop through each element in the matrix using a single loop.
  2. 2Step 2: For each element at position (i, j), check if it is a diagonal element (i == j or i == n - 1 - j).
  3. 3Step 3: If it is a diagonal element, ensure it is non-zero; if it is not a diagonal element, ensure it is zero.
  4. 4Step 4: If any condition fails, return false. If all checks pass, return true.
solution.py11 lines
1# Full working Python code
2
3def checkXMatrix(grid):
4    n = len(grid)
5    for i in range(n):
6        if grid[i][i] == 0 or grid[i][n - 1 - i] == 0:
7            return False
8        for j in range(n):
9            if (j != i and j != n - 1 - i) and grid[i][j] != 0:
10                return False
11    return True

Complexity note: The time complexity remains O(n²) since we still need to check each element of the matrix. The space complexity is O(1) as we are not using any additional data structures.

  • 1Diagonal elements must be non-zero while non-diagonal elements must be zero.
  • 2Understanding the structure of the matrix helps in efficiently checking the conditions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.