Skip to content
Related Articles

Related Articles

Find if given matrix is Toeplitz or not
  • Difficulty Level : Easy
  • Last Updated : 26 Nov, 2020

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 },
                    { 2, 0, 1, 4 }};
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 isToepliz(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 (isToepliz(mat))
        cout << "Matrix is a Toepliz ";
    else
        cout << "Matrix is not a Toepliz ";
 
    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 isToepliz(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 (isToepliz(mat))
            System.out.println("Matrix is a Toepliz ");
        else
            System.out.println("Matrix is not a Toepliz ");
    }
}
 
// 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 isToepliz(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 (isToepliz(mat))
            Console.WriteLine("Matrix is a Toepliz ");
        else
            Console.WriteLine("Matrix is not a Toepliz ");
    }
}
 
// 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 isToepliz($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 (isToepliz($mat))
    echo "Matrix is a Toepliz ";
else
    echo "Matrix is not a Toepliz ";
 
// This code is contributed
// by nitin mittal.
?>


Output



Matrix is a Toepliz

The time complexity of this solution would be O(n2) as we are traversing each element in the matrix once only.
Reference: https://en.wikipedia.org/wiki/Toeplitz_matrix

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


Output

Yes

Time Complexity: O(mn), where m is number of rows and n is number of columns.
Space Complexity: 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 Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

 

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :