We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Matrix Is X-Matrix

Number: 2398

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an n x n square matrix, determine if it is an X-Matrix. A matrix is an X-Matrix if:

  1. All the elements on both diagonals (primary and secondary) are non-zero.
  2. 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.

Code Solutions

# Define a function to check if a matrix is an X-Matrix
def checkXMatrix(grid):
    # Determine the size of the matrix
    n = len(grid)
    # Iterate over each row
    for i in range(n):
        # Iterate over each column in the row
        for j in range(n):
            # Check if the current element is on either diagonal
            if i == j or i + j == n - 1:
                # Diagonal elements must be non-zero
                if grid[i][j] == 0:
                    return False
            else:
                # Off-diagonals must be zero
                if grid[i][j] != 0:
                    return False
    # If all conditions are satisfied, return True
    return True

# Example usage:
grid_example = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]
print(checkXMatrix(grid_example))  # Expected output: True
← Back to All Questions