Given an M × N matrix, check if it is a Toeplitz matrix or not. A Toeplitz matrix or diagonal-constant matrix is a matrix in which each descending diagonal from left to right is constant.

Any M × N matrix mat is a Toeplitz matrix if mat(i, j) = mat(i+1, j+1) = mat(i+2, j+2), and so on… Here, mat(i, j) denotes the element mat[i][j] in the matrix.

For instance, the following matrix is a Toeplitz matrix:

Toeplitz Matrix

Practice this problem

 
The idea is simple – traverse the matrix once, and for each element (i, j), check if it is the same as its immediate diagonal element (i+1, j+1) or not. If any element differs from its immediate diagonal element, the matrix cannot be Toeplitz.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

Toeplitz matrix

Java


Download  Run Code

Output:

Toeplitz matrix

Python


Download  Run Code

Output:

Toeplitz matrix

The time complexity of the proposed solution is O(N2) for an N × N matrix and doesn’t require any extra space.

 
References: https://en.wikipedia.org/wiki/Toeplitz_matrix