LeetCode 2319: Check if Matrix Is X-Matrix Solution

Master LeetCode problem 2319 (Check if Matrix Is X-Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2319. Check if Matrix Is X-Matrix

Problem Explanation

Explanation

To determine if a given square matrix is an X-Matrix, we need to check two conditions:

  1. All elements in the main diagonal and anti-diagonal should be non-zero.
  2. All other elements should be zero.

We can iterate through the matrix and check these conditions. If any element violates these conditions, we can immediately return false. Otherwise, we return true.

Time Complexity: O(n^2) where n is the size of the matrix. Space Complexity: O(1)

Solution Code

class Solution {
    public boolean isXMatrix(int[][] grid) {
        int n = grid.length;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if ((i == j || i + j == n - 1) && grid[i][j] == 0) {
                    return false;
                } else if (i != j && i + j != n - 1 && grid[i][j] != 0) {
                    return false;
                }
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2319 (Check if Matrix Is X-Matrix)?

This page provides optimized solutions for LeetCode problem 2319 (Check if Matrix Is X-Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2319 (Check if Matrix Is X-Matrix)?

The time complexity for LeetCode 2319 (Check if Matrix Is X-Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2319 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2319 in Java, C++, or Python.

Back to LeetCode Solutions