A Toeplitz matrix (or diagonal-constant matrix) is a matrix where every diagonal from top-left to bottom-right contains the same elements.

Your task is to check whether a given matrix satisfies this property.

Problem Statement

Given a matrix mat, return:

Key Idea

A matrix is Toeplitz if:

Every element is equal to the element diagonally top-left of it.

So for every cell (i, j):

mat[i][j] == mat[i-1][j-1]

We just need to verify this for all valid positions.

Java Solution

class Solution {
    public boolean isToeplitz(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;

        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                if (mat[i][j] != mat[i - 1][j - 1]) {
                    return false;
                }
            }
        }

        return true;
    }
}

How the Code Works

Step 1: Traverse matrix

for (int i = 1; i < n; i++)
for (int j = 1; j < m; j++)

We start from 1 because:

Step 2: Check diagonal condition

if (mat[i][j] != mat[i - 1][j - 1])

We compare each element with its top-left diagonal neighbor.

Step 3: If all checks pass

return true;

The matrix satisfies Toeplitz property.

Example 1 (True Case)

Input

6 7 8
4 6 7
1 4 6

Diagonals

Output

true

Example 2 (False Case)

Input

6 3 8
4 9 7
1 4 6

Problem:

Output

false

Complexity Analysis

Conclusion

The Toeplitz matrix check is a simple yet important matrix problem. The core idea is just verifying the top-left diagonal consistency, making it efficient and easy to implement.