VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-if-given-matrix-is-toeplitz-or-not/

⇱ Toeplitz Matrix or Not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toeplitz Matrix or Not

Last Updated : 10 Apr, 2026

Given a square matrix mat[][] of order n, check if it is a Toeplitz Matrix.

Note: A Toeplitz matrix - also called a diagonal-constant matrix - is a matrix where elements of every individual descending diagonal are same from left to right. Equivalently, for any entry mat[i][j], it is same as mat[i-1][j-1] or mat[i-2][j-2] and so on. We can get a better idea using the following image, all same colored cells should have same values.

👁 Image

Examples:

Input: mat[][] = [ [6, 7, 8]
[4, 6, 7]
[1, 4, 6] ]
Output: Yes
Explanation: All the diagonals of the given matrix are [6, 6, 6], [7, 7], [8], [4, 4], [1]. For every diagonal, as all the elements are same, the given matrix is Toeplitz Matrix.

Input: mat[][] = [ [6, 3, 8]
[4, 9, 7]
[1, 4, 6] ]
Output: No
Explanation: The primary diagonal elements of the given matrix are [6, 9, 6]. As the diagonal elements are not same, the given matrix is not Toeplitz Matrix.

[Expected Approach - 1] - Checking Each Diagonal - O(n × n) Time and O(1) Space

Traverse every downward-sloping diagonal in the matrix by using each element in the first row and each element in the first column as a starting point, and verify that every element along that diagonal matches the value at its head.

Follow the below given steps:

  • Let n = mat.size() and m = mat[0].size().
  • Check all diagonals starting from the first row and first column using checkDiagonal; if any call returns false, return false.
  • If all calls to checkDiagonal succeed, return true.
  • In checkDiagonal(mat, x, y), compare mat[i][j] to mat[x][y] for each i = x+1, j = y+1 while i < n && j < m; return false on the first mismatch, otherwise return true after reaching the edge.

Output
true

[Expected Approach - 2] - Checking Diagonally Above Element - O(n × n) Time and O(1) Space

The core idea is to examine each cell, starting from the second row and second column. We compare each cell's value with its top-left neighbor. If a mismatch is found, the matrix is not Toeplitz, and we can stop. If the entire matrix is checked without any mismatches, all diagonals are constant.

Follow the below given steps:

  • Let n = mat.size() and m = mat[0].size().
  • Iterate i from 1 to n - 1 and within that j from 1 to m - 1.
  • If mat[i][j] != mat[i - 1][j - 1] at any point, return false.
  • Once all pairs have been checked with no mismatches, return true.

Output
true
Comment
Article Tags:
Article Tags: