Problem 2319

Abstract / Summary

Verify if all diagonal entries are one value and all non-diagonal entries are another value in a square matrix.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 2319.py

class Solution:
    def checkXMatrix(self, grid: List[List[int]]) -> bool:
        size = len(grid)
        for y in range(size):
            for x in range(size):
                diagonal = (x == y or x == size - y - 1)
                positive = (grid[y][x] != 0)
                if diagonal ^ positive:
                    return False
        return True
10 lines | 369 bytes | submitted February 4, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method checkXMatrix that determines whether a square matrix satisfies the “X-matrix” property. An X-matrix requires all elements on both main diagonals to be non-zero while every other element must be zero. The method receives the matrix as a list of lists, computes its dimension, iterates over each cell, evaluates the diagonal condition, and returns a Boolean result.

Key Steps

Determining the matrix size

size = len(grid)

The code assumes a square matrix and captures the dimension once, avoiding repeated length calculations during iteration.

Iterating over rows and columns

for y in range(size):
    for x in range(size):

Two nested loops walk through every coordinate (x, y). By using range(size) the loops are bounded by the matrix dimension, guaranteeing coverage of all cells.

Identifying diagonal positions

diagonal = (x == y or x == size - y - 1)

A cell belongs to one of the two main diagonals if its column index equals its row index (x == y) or if it mirrors the opposite diagonal (x == size - y - 1). This single Boolean expression captures both diagonals without separate checks.

Checking the required value condition

positive = (grid[y][x] != 0)

The variable positive records whether the current element is non-zero. The X-matrix rule demands non-zero values exactly on diagonal cells.

Combining the two conditions

if diagonal ^ positive:
    return False

The exclusive-or (^) operator yields True when exactly one of the operands is true. Therefore, the statement detects any mismatch: a diagonal cell that is zero or a non-diagonal cell that is non-zero. Encountering such a mismatch triggers an early exit with False.

Final result

return True

If the loops complete without finding a mismatch, every cell conforms to the X-matrix definition, and the method returns True.

Edge Cases Handled

The algorithm correctly processes a 1×1 matrix. In that scenario size equals 1, the only cell satisfies both diagonal conditions (x == y and x == size - y - 1 are both true), and the exclusive-or check passes only if the single element is non-zero, matching the X-matrix rule.

When the matrix contains rows of varying lengths, the initial size = len(grid) still reflects the number of rows, but the inner indexing grid[y][x] would raise an exception if a row is shorter than size. The code implicitly assumes well-formed square input, which is typical for this problem domain.

All zero matrices are rejected unless the size is zero, because every diagonal cell would be zero, causing the exclusive-or condition to trigger on the first diagonal element.

Performance Optimizations

The implementation performs a single pass over the matrix, visiting each element exactly once. By computing size once and reusing it, the code avoids repeated length calculations inside the loops. The use of the exclusive-or operator consolidates the two logical checks into a single conditional, reducing branching overhead. Early termination on the first violation prevents unnecessary work on large matrices that fail early, contributing to efficient average-case performance. The algorithm’s memory footprint is constant, relying only on a few scalar variables regardless of matrix size.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a square grid that looks like a big game board filled with numbers. This code acts like a tiny helper that checks if the board follows a special rule. The rule is that all the numbers on the two big diagonal lines forming an X shape must be bigger than zero, while every other spot on the board outside of those lines must be exactly zero.

The computer starts at the top left corner of the board and visits every single square one by one. For each square, it looks at the numbers to see if they are in the right place. It checks if the current spot is part of that X shape or if it is just one of the empty spots. If it finds a number in a spot where it should be empty, or if it finds an empty spot where a number belongs, the code raises a flag to say that the board does not follow the rule. If it walks through the whole board and everyone is in the right spot, the job is finished.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.07

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java Python C++ TS
WalkCCC Java Python C++
leetcode.ca Java Python C++ C C# Go Rust TS
Progiez Java Python C++
github charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
lkwq007 Python
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
lkwq007 Python
varunu28 Java
26 links | 12 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 2 medium
5 solutions   February 4, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality