Last Updated: 9 Jan, 2022

Toeplitz Matrix

Easy
Asked in companies
FacebookAmazonGoogle inc

Problem statement

You are given a matrix of size N * M. You have to find out whether the matrix is Toeplitz or not.

A Matrix is said to be Toeplitz if every diagonal from top-left to bottom-right has the same elements.

You are given the matrix ‘MAT’ of size N * M.Your task is to find out whether it is Toeplitz or not.

For Example
 The given matrix is Toeplitz:

altImage

Input Format:
The first line of the input contains an integer, 'T,’ denoting the number of test cases.

The first line of each test case contains two integers,' N’ and ‘M’ denoting the number of rows and columns.

The next line of each test case has ‘N’ lines that have M values corresponding to the matrix ‘MAT’.
Output Format:
For each test case, print ‘YES’ or ‘NO’ whether the matrix is Toeplitz or not.

 Print the output of each test case in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 1000.
1 <= M <= 1000.

Time limit: 1 sec

Approaches

01 Approach

In this approach, we will iterate all the diagonals and if we found any element mismatched, the matrix is not Toeplitz. Otherwise, the matrix is Toeplitz.

If all diagonal elements are identical then they should follow :

MAT[i][j] == MATt[i-1][j-1].

 

Algorithm:

 

  • For i in range(1,n-1):
    • For j in range(1,m-1):
      • If MAT[i][j] is not equal to  MAT[i-1][j-1]:
        • Found a mismatched element.
        • Return False
  • Otherwise, the matrix is Toeplitz.
  • Return True.