LeetCode 2319. Check if Matrix Is X-Matrix Java Solution

·

2 min read

Problem Description

  • Problem: Check if Matrix is X-Matrix

  • Description: Determine if a given square matrix is an X-matrix. An X-matrix has all elements zero except those on the main diagonal and the anti-diagonal.

Approach

  • Idea: To check if each element meets the conditions of an X-matrix, inspect the main and anti-diagonals.

  • Algorithm: Verify that all elements not on the main or anti-diagonals are zero to determine if it's an X-matrix.

Code

class Solution {
    public boolean checkXMatrix(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) {  // Element belongs to the main or anti-diagonal
                    if (grid[i][j] == 0) return false;  // If zero, not an X-matrix
                } else {  // Element does not belong to the diagonals
                    if (grid[i][j] != 0) return false;  // If not zero, not an X-matrix
                }
            }
        }

        return true;  // If all conditions are satisfied, it is an X-matrix
    }
}

Conclusion

  • Time Complexity: This algorithm checks each element of the matrix once, so it is O(n^2).

  • Space Complexity: It uses no additional space apart from the input matrix, so it is O(1).

Re-solved this question. Last time was too complicate. I believe this way is better.

Did you find this article valuable?

Support Eunhan's blog by becoming a sponsor. Any amount is appreciated!