Find if given matrix is Toeplitz or not
Given a square matrix, find if it’s a Toeplitz matrix or not. A Toeplitz (or diagonal-constant) matrix is a matrix in which each descending diagonal from left to right is constant, i.e., all elements in a diagonal are same.
In general, any n×n matrix mat[][] is a Toeplitz matrix if every cell mat[i][j] is same as mat[i-1][j-1], mat[i+1][j+1], mat[i-2][j-2], mat[i+2][j+2], .. for every cell mat[i][j] and all the valid cells mat[i+k][j+k] or mat[i-k][j-k]
Examples :
Input: mat[N][N] = {{ 6, 7, 8}, { 4, 6, 7}, { 1, 4, 6}}, Output : True; Values in all diagonals are same. Input: mat[N][N] = {{ 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }}; Output : True; Input: mat[N][N] = {{ 6, 3, 8}, { 4, 9, 7}, { 1, 4, 6}}, Output : False;
The idea is very simple. For each element of first row and first column(or last row and last column) in the matrix, we check if descending diagonal starting from that element have same values or not. If we found any diagonal having different values, we return false.
Below is the implementation of the above code:
C++
// C++ program to check whether given matrix // is a Toeplitz matrix or not #include <iostream> using namespace std; #define N 5 #define M 4 // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not bool checkDiagonal( int mat[N][M], int i, int j) { int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false ; } // we only reach here when all elements // in given diagonal are same return true ; } // Function to check whether given matrix is a // Toeplitz matrix or not bool isToeplitz( int mat[N][M]) { // do for each element in first row for ( int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false ; } // do for each element in first column for ( int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false ; } // we only reach here when each descending // diagonal from left to right is same return true ; } // Driver code int main() { int mat[N][M] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) cout << "Matrix is a Toeplitz " ; else cout << "Matrix is not a Toeplitz " ; return 0; } |
Java
// Java program to check whether given matrix // is a Toeplitz matrix or not import java.io.*; class GFG { public static int N = 5 ; public static int M = 4 ; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not static boolean checkDiagonal( int mat[][], int i, int j) { int res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false ; } // we only reach here when all elements // in given diagonal are same return true ; } // Function to check whether given matrix is a // Toeplitz matrix or not static boolean isToeplitz( int mat[][]) { // do for each element in first row for ( int i = 0 ; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0 , i)) return false ; } // do for each element in first column for ( int i = 1 ; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0 )) return false ; } // we only reach here when each descending // diagonal from left to right is same return true ; } // Driver code public static void main(String[] args) { int mat[][] = { { 6 , 7 , 8 , 9 }, { 4 , 6 , 7 , 8 }, { 1 , 4 , 6 , 7 }, { 0 , 1 , 4 , 6 }, { 2 , 0 , 1 , 4 } }; // Function call if (isToeplitz(mat)) System.out.println( "Matrix is a Toeplitz " ); else System.out.println( "Matrix is not a Toeplitz " ); } } // This code is contributed by Pramod Kumar |
Python3
# Python3 program to check whether given # matrix is a Toeplitz matrix or not N = 5 M = 4 # Function to check if all elements present in # descending diagonal starting from position # (i, j) in the matrix are all same or not def checkDiagonal(mat, i, j): res = mat[i][j] i + = 1 j + = 1 while (i < N and j < M): # mismatch found if (mat[i][j] ! = res): return False i + = 1 j + = 1 # we only reach here when all elements # in given diagonal are same return True # Function to check whether given # matrix is a Toeplitz matrix or not def isToeplitz(mat): # do for each element in first row for j in range (M): # check descending diagonal starting from # position (0, j) in the matrix if not (checkDiagonal(mat, 0 , j)): return False # do for each element in first column for i in range ( 1 , N): # check descending diagonal starting # from position (i, 0) in the matrix if not (checkDiagonal(mat, i, 0 )): return False return True # Driver Code if __name__ = = "__main__" : mat = [[ 6 , 7 , 8 , 9 ], [ 4 , 6 , 7 , 8 ], [ 1 , 4 , 6 , 7 ], [ 0 , 1 , 4 , 6 ], [ 2 , 0 , 1 , 4 ]] # Function call if (isToeplitz(mat)): print ( "Matrix is a Toeplitz" ) else : print ( "Matrix is not a Toeplitz" ) # This code is contributed by Jasmine K Grewal |
C#
// C# program to check whether given matrix // is a Toeplitz matrix or not using System; class GFG { public static int N = 5; public static int M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not static bool checkDiagonal( int [, ] mat, int i, int j) { int res = mat[i, j]; while (++i < N && ++j < M) { // mismatch found if (mat[i, j] != res) return false ; } // we only reach here when all elements // in given diagonal are same return true ; } // Function to check whether given matrix is a // Toeplitz matrix or not static bool isToeplitz( int [, ] mat) { // do for each element in first row for ( int i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false ; } // do for each element in first column for ( int i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false ; } // we only reach here when each descending // diagonal from left to right is same return true ; } // Driver code public static void Main() { int [, ] mat = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) Console.WriteLine( "Matrix is a Toeplitz " ); else Console.WriteLine( "Matrix is not a Toeplitz " ); } } // This code is contributed by KRV. |
PHP
<?php // PHP program to check whether // given matrix is a Toeplitz // matrix or not // Function to check if all // elements present in descending // diagonal starting from position // (i, j) in the matrix are all // same or not function checkDiagonal( $mat , $i , $j ) { $N = 5; $M = 4; $res = $mat [ $i ][ $j ]; while (++ $i < $N && ++ $j < $M ) { // mismatch found if ( $mat [ $i ][ $j ] != $res ) return false; } // we only reach here when // all elements in given // diagonal are same return true; } // Function to check whether // given matrix is a // Toeplitz matrix or not function isToeplitz( $mat ) { $N = 5; $M = 4; // do for each element in first row for ( $i = 0; $i < $M ; $i ++) { // check descending diagonal // starting from position // (0, j) in the matrix if (!checkDiagonal( $mat , 0, $i )) return false; } // do for each element // in first column for ( $i = 1; $i < $N ; $i ++) { // check descending diagonal // starting from position // (i, 0) in the matrix if (!checkDiagonal( $mat , $i , 0)) return false; } // we only reach here when // each descending diagonal // from left to right is same return true; } // Driver code $mat = array ( array ( 6, 7, 8, 9 ), array ( 4, 6, 7, 8 ), array ( 1, 4, 6, 7 ), array ( 0, 1, 4, 6 ), array ( 2, 0, 1, 4 )); // Function call if (isToeplitz( $mat )) echo "Matrix is a Toeplitz " ; else echo "Matrix is not a Toeplitz " ; // This code is contributed // by nitin mittal. ?> |
Javascript
<script> // Javascript program to check whether given matrix // is a Toeplitz matrix or not let N = 5; let M = 4; // Function to check if all elements present in // descending diagonal starting from position // (i, j) in the matrix are all same or not function checkDiagonal(mat, i, j) { let res = mat[i][j]; while (++i < N && ++j < M) { // mismatch found if (mat[i][j] != res) return false ; } // we only reach here when all elements // in given diagonal are same return true ; } // Function to check whether given matrix is a // Toeplitz matrix or not function isToeplitz(mat) { // do for each element in first row for (let i = 0; i < M; i++) { // check descending diagonal starting from // position (0, j) in the matrix if (!checkDiagonal(mat, 0, i)) return false ; } // do for each element in first column for (let i = 1; i < N; i++) { // check descending diagonal starting from // position (i, 0) in the matrix if (!checkDiagonal(mat, i, 0)) return false ; } // we only reach here when each descending // diagonal from left to right is same return true ; } let mat = [ [ 6, 7, 8, 9 ], [ 4, 6, 7, 8 ], [ 1, 4, 6, 7 ], [ 0, 1, 4, 6 ], [ 2, 0, 1, 4 ] ]; // Function call if (isToeplitz(mat)) document.write( "Matrix is a Toeplitz " ); else document.write( "Matrix is not a Toeplitz " ); </script> |
Matrix is a Toeplitz
The time complexity of this solution would be O(mn) where m is number of rows and n is number of columns as we are traversing through each element of the matrix.
Auxiliary Space: O(1), since no extra space has been taken.
This approach can further be improved:
As we can see that we are traversing through entire matrix so we will keep track of each element if it is equal to its diagonally above element or not. If any element fails this condition this means matrix is not “Toeplitz” so return false or if all elements pass this condition then return true.
C++
#include <iostream> using namespace std; #define N 5 #define M 4 bool isToeplitz( int matrix[N][M]) { for ( int i = 1; i < N; i++) { for ( int j = 1; j < M; j++) { // check if each index is equal to its // diagonally upper index if not return false if (matrix[i][j] != matrix[i - 1][j - 1]) return false ; } } return true ; } // Driver code int main() { int mat[N][M] = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) cout << "Matrix is a Toeplitz " ; else cout << "Matrix is not a Toeplitz " ; return 0; } //This code is contributed by Harsh Singh NIT Sgr |
Java
// Java program to check whether given matrix // is a Toeplitz matrix or not import java.io.*; class GFG { public static int N = 5 ; public static int M = 4 ; // Function to check whether given matrix is a // Toeplitz matrix or not static boolean isToeplitz( int mat[][]) { for ( int i = 1 ; i < N; i++) { for ( int j = 1 ; j < M; j++) { // check if each index is equal to its // diagonally upper index if not return false if (mat[i][j] != mat[i - 1 ][j - 1 ]) { return false ; } } } return true ; } // Driver code public static void main(String[] args) { int mat[][] = { { 6 , 7 , 8 , 9 }, { 4 , 6 , 7 , 8 }, { 1 , 4 , 6 , 7 }, { 0 , 1 , 4 , 6 }, { 2 , 0 , 1 , 4 } }; // Function call if (isToeplitz(mat)) System.out.println( "Matrix is a Toeplitz " ); else System.out.println( "Matrix is not a Toeplitz " ); } } // This code is contributed by Harsh Singh NIT Sgr |
Python3
N = 5 ; M = 4 ; def isToeplitz( matrix): for i in range ( 1 ,N): for j in range ( 1 ,M): # check if each index is equal to its # diagonally upper index if not return false if (matrix[i][j] ! = matrix[i - 1 ][j - 1 ]): return False ; return True ; # Driver code mat = [ [ 6 , 7 , 8 , 9 ], [ 4 , 6 , 7 , 8 ], [ 1 , 4 , 6 , 7 ], [ 0 , 1 , 4 , 6 ], [ 2 , 0 , 1 , 4 ] ]; # Function call if (isToeplitz(mat)): print ( "Matrix is a Toeplitz " ); else : print ( "Matrix is not a Toeplitz " ); |
C#
// C# program to check whether given matrix // is a Toeplitz matrix or not using System; class GFG { public static int N = 5; public static int M = 4; // Function to check whether given matrix is a // Toeplitz matrix or not static bool isToeplitz( int [, ] mat) { for ( int i = 1; i < N; i++) { for ( int j = 1; j < M; j++) { // check if each index is equal to its // diagonally upper index if not return // false if (mat[i, j] != mat[i - 1, j - 1]) { return false ; } } } return true ; } // Driver code public static void Main( string [] args) { int [, ] mat = { { 6, 7, 8, 9 }, { 4, 6, 7, 8 }, { 1, 4, 6, 7 }, { 0, 1, 4, 6 }, { 2, 0, 1, 4 } }; // Function call if (isToeplitz(mat)) Console.WriteLine( "Matrix is a Toeplitz " ); else Console.WriteLine( "Matrix is not a Toeplitz " ); } } // This code is contributed by Karandeep1234 |
Javascript
const N = 5 const M = 4 function isToeplitz(matrix) { for (let i = 1; i < N; i++) { for (let j = 1; j < M; j++) { // check if each index is equal to its // diagonally upper index if not return false if (matrix[i][j] != matrix[i - 1][j - 1]) return false ; } } return true ; } // Driver code let mat = [ [ 6, 7, 8, 9 ], [ 4, 6, 7, 8 ], [ 1, 4, 6, 7 ], [ 0, 1, 4, 6 ], [ 2, 0, 1, 4 ] ]; // Function call if (isToeplitz(mat)) document.write( "Matrix is a Toeplitz " ); else document.write( "Matrix is not a Toeplitz " ); |
Matrix is a Toeplitz
Time complexity of this solution would be O(mn) where m is number of rows and n is number of columns as we are traversing through each element of the matrix.
Auxiliary Space: O(1), since no extra space has been taken.
Hashing based approach:
Consider an element at index (i, j) of matrix of dimension (m, n). For the matrix to be diagonal-constant, all the elements in the diagonal must be same. Consider the diagonal containing this (i, j) element. The other elements in this diagonal will have their index of the form (i+k, j+k) or (i-k, j-k). Notice that whatever x-value and y-value of these indexes are, their difference is always the same. i.e. (i+k)-(j+k) == (i-k)-(j-k) == i-j.
The diagram below gives a better visualization of this idea. Consider the diagonal coloured yellow. The difference between x-value and y-value of any index on this diagonal is 2 (2-0, 3-1, 4-2, 5-3). Same can be observed for all body diagonals.

Index of a Toeplitz matrix
For red-coloured diagonal, difference is 3. For green-coloured diagonal, difference is 0. For orange-coloured diagonal, difference is -2 and so on…
The idea is to exploit the fact that for a Toeplitz matrix, these individual index differences for particular diagonals will be unique. And since it is a constant-diagonal matrix, for all these unique keys, there should be unique values same as any element on that diagonal. So, we create a HashMap to store these (key, value) pairs. At any moment if we encounter a value, that is different from it’s corresponding stored key value, we return false.
Below is the implementation of the above code:
C++
// C++ program to check whether given // matrix is a Toeplitz matrix or not #include <bits/stdc++.h> using namespace std; bool isToeplitz(vector<vector< int >> matrix) { // row = number of rows // col = number of columns int row = matrix.size(); int col = matrix[0].size(); // HashMap to store key,value pairs map< int , int > Map; for ( int i = 0; i < row; i++) { for ( int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (Map[key]) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (Map[key] != matrix[i][j]) return false ; } // Else we put key,value pair in hashmap else { Map[i - j] = matrix[i][j]; } } } return true ; } // Driver code int main() { vector<vector< int >> matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? "Yes" : "No" ; cout << result; return 0; } // This code is contributed by divyesh072019 |
Java
// JAVA program to check whether given matrix // is a Toeplitz matrix or not import java.util.*; class GFG { static boolean isToeplitz( int [][] matrix) { // row = number of rows // col = number of columns int row = matrix.length; int col = matrix[ 0 ].length; // HashMap to store key,value pairs HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for ( int i = 0 ; i < row; i++) { for ( int j = 0 ; j < col; j++) { int key = i - j; // if key value exists in the hashmap, if (map.containsKey(key)) { // we check whether the current value // stored in this key matches to element // at current index or not. If not, // return false if (map.get(key) != matrix[i][j]) return false ; } // else we put key,value pair in hashmap else { map.put(i - j, matrix[i][j]); } } } return true ; } // Driver Code public static void main(String[] args) { int [][] matrix = { { 12 , 23 , - 32 }, { - 20 , 12 , 23 }, { 56 , - 20 , 12 }, { 38 , 56 , - 20 } }; // Function call String result = (isToeplitz(matrix)) ? "Yes" : "No" ; System.out.println(result); } } |
Python3
# Python3 program to check whether given matrix # is a Toeplitz matrix or not def isToeplitz(matrix): # row = number of rows # col = number of columns row = len (matrix) col = len (matrix[ 0 ]) # dictionary to store key,value pairs map = {} for i in range (row): for j in range (col): key = i - j # if key value exists in the map, if (key in map ): # we check whether the current value stored # in this key matches to element at current # index or not. If not, return false if ( map [key] ! = matrix[i][j]): return False # else we put key,value pair in map else : map [key] = matrix[i][j] return True # Driver Code if __name__ = = "__main__" : matrix = [[ 12 , 23 , - 32 ], [ - 20 , 12 , 23 ], [ 56 , - 20 , 12 ], [ 38 , 56 , - 20 ]] # Function call if (isToeplitz(matrix)): print ( "Yes" ) else : print ( "No" ) |
C#
// C# program to check whether given // matrix is a Toeplitz matrix or not using System; using System.Collections.Generic; class GFG{ static bool isToeplitz( int [,] matrix) { // row = number of rows // col = number of columns int row = matrix.GetLength(0); int col = matrix.GetLength(1); // HashMap to store key,value pairs Dictionary< int , int > map = new Dictionary< int , int >(); for ( int i = 0; i < row; i++) { for ( int j = 0; j < col; j++) { int key = i - j; // If key value exists in the hashmap, if (map.ContainsKey(key)) { // We check whether the current value // stored in this key matches to element // at current index or not. If not, // return false if (map[key] != matrix[i, j]) return false ; } // Else we put key,value pair in hashmap else { map.Add(i - j, matrix[i, j]); } } } return true ; } // Driver code static void Main() { int [,] matrix = { { 12, 23, -32 }, { -20, 12, 23 }, { 56, -20, 12 }, { 38, 56, -20 } }; // Function call string result = (isToeplitz(matrix)) ? "Yes" : "No" ; Console.WriteLine(result); } } // This code is contributed by divyeshrabadiya07 |
Javascript
<script> // JavaScript program to check whether given // matrix is a Toeplitz matrix or not function isToeplitz(matrix) { // row = number of rows // col = number of columns let row = matrix.length; let col = matrix[0].length; // HashMap to store key,value pairs let map = new Map(); for (let i = 0; i < row; i++) { for (let j = 0; j < col; j++) { let key = i - j; // If key value exists in the hashmap, if (map.has(key)) { // We check whether the current // value stored in this key // matches to element at current // index or not. If not, return // false if (map.get(key) != matrix[i][j]) return false ; } // Else we put key,value pair in hashmap else { map.set(i - j, matrix[i][j]); } } } return true ; } // Driver code let matrix = [ [ 12, 23, -32 ], [ -20, 12, 23 ], [ 56, -20, 12 ], [38, 56, -20 ] ]; // Function call let result = (isToeplitz(matrix)) ? "Yes" : "No" ; document.write(result); </script> |
Yes
Time Complexity: O(mn), where m is number of rows and n is number of columns.
Auxiliary Space: O(m+n), because at worst case, if a matrix is Toeplitz, we have store exactly (m+n-1) key, value pairs. (In first row we have n distinct keys and then for next each m-1 rows, we keep adding one unique key to the map.
This article is contributed by Aarti_Rathi and Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...