A clear explanation of checking whether every top-left to bottom-right diagonal in a matrix has the same value.
Problem Restatement
We are given an m x n matrix.
Return True if the matrix is Toeplitz. Otherwise, return False.
A matrix is Toeplitz if every diagonal from top-left to bottom-right contains the same value. In other words, each cell should match the cell directly above-left from it.
Input and Output
| Item | Meaning |
|---|---|
| Input | An integer matrix matrix |
| Output | True if the matrix is Toeplitz, otherwise False |
| Diagonal direction | Top-left to bottom-right |
| Main rule | matrix[r][c] == matrix[r - 1][c - 1] for all valid r, c |
Example function shape:
def isToeplitzMatrix(matrix: list[list[int]]) -> bool:
...Examples
Example 1:
matrix = [
[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2],
]Output:
TrueThe diagonals are:
[9]
[5, 5]
[1, 1, 1]
[2, 2, 2]
[3, 3]
[4]Every diagonal has equal values, so the matrix is Toeplitz.
Example 2:
matrix = [
[1, 2],
[2, 2],
]Output:
FalseThe diagonal from top-left to bottom-right is:
[1, 2]The values are different, so the matrix is not Toeplitz.
First Thought: Check Each Diagonal
One direct way is to start every diagonal from the first row and first column.
Then follow each diagonal down-right and check whether every value is the same.
This works, but there is an even simpler way.
Every cell belongs to exactly one top-left to bottom-right diagonal. For a diagonal to be valid, every cell except the first cell on that diagonal must equal its previous diagonal neighbor.
So instead of explicitly listing diagonals, we can compare each cell with its upper-left neighbor.
Key Insight
A matrix is Toeplitz exactly when this condition holds for every cell not in the first row or first column:
matrix[r][c] == matrix[r - 1][c - 1]Why?
If every cell equals the previous cell on its diagonal, then by repeated equality, all cells on that diagonal are equal.
So we only need one pass through the matrix.
Algorithm
- Let
rows = len(matrix). - Let
cols = len(matrix[0]). - For every row
rfrom1torows - 1:- For every column
cfrom1tocols - 1:- Compare
matrix[r][c]withmatrix[r - 1][c - 1]. - If they are different, return
False.
- Compare
- For every column
- If no mismatch is found, return
True.
Correctness
The algorithm checks every cell that has an upper-left neighbor.
If it finds a cell matrix[r][c] where:
matrix[r][c] != matrix[r - 1][c - 1]then the diagonal containing those two cells has different values. Therefore, the matrix is not Toeplitz, and returning False is correct.
If the algorithm finishes without finding any mismatch, then every cell equals its upper-left neighbor. Along any top-left to bottom-right diagonal, each value equals the value before it. By transitivity, all values on that diagonal are equal.
Therefore, every diagonal satisfies the Toeplitz condition, so returning True is correct.
Complexity
Let:
m = number of rows
n = number of columns| Metric | Value | Why |
|---|---|---|
| Time | O(m * n) | Each non-first-row and non-first-column cell is checked once |
| Space | O(1) | Only loop variables are used |
Implementation
class Solution:
def isToeplitzMatrix(self, matrix: list[list[int]]) -> bool:
rows = len(matrix)
cols = len(matrix[0])
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] != matrix[r - 1][c - 1]:
return False
return TrueCode Explanation
We first get the matrix dimensions:
rows = len(matrix)
cols = len(matrix[0])Then we start from row 1 and column 1 because cells in row 0 or column 0 do not have an upper-left neighbor.
for r in range(1, rows):
for c in range(1, cols):For each cell, we compare it with the previous cell on the same diagonal:
if matrix[r][c] != matrix[r - 1][c - 1]:
return FalseIf any comparison fails, the matrix cannot be Toeplitz.
If all comparisons pass:
return Truethe matrix is Toeplitz.
Testing
def run_tests():
s = Solution()
assert s.isToeplitzMatrix([
[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2],
]) is True
assert s.isToeplitzMatrix([
[1, 2],
[2, 2],
]) is False
assert s.isToeplitzMatrix([
[7],
]) is True
assert s.isToeplitzMatrix([
[1, 2, 3],
]) is True
assert s.isToeplitzMatrix([
[1],
[2],
[3],
]) is True
assert s.isToeplitzMatrix([
[1, 2, 3],
[4, 1, 2],
[5, 4, 1],
]) is True
print("all tests passed")
run_tests()Test meaning:
| Test | Why |
|---|---|
| Standard Toeplitz matrix | Confirms all diagonals match |
| Mismatch on main diagonal | Confirms false case |
| Single cell | Always Toeplitz |
| Single row | Every diagonal has one value |
| Single column | Every diagonal has one value |
| Square Toeplitz matrix | Confirms repeated diagonal comparison |