Java  

Toeplitz Matrix Check in Java

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:

  • true → if it is a Toeplitz matrix

  • false → otherwise

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:

  • First row and first column have no top-left diagonal element.

Step 2: Check diagonal condition

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

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

  • If any mismatch is found → not Toeplitz → return false

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

  • 6 → 6 → 6

  • 7 → 7

  • 4 → 4

Output

true

Example 2 (False Case)

Input

6 3 8
4 9 7
1 4 6

Problem:

  • Diagonal: 6 → 9 → 6 (not equal)

Output

false

Complexity Analysis

  • Time Complexity: O(n × m)
    → Each element is checked once

  • Auxiliary Space: O(1)
    → No extra data structure used

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.