Program to check whether given matrix is Toeplitz Matrix or not in Python

A Toeplitz matrix is a square matrix where every diagonal descending from left to right has the same value. In other words, all elements along each diagonal from top-left to bottom-right are identical.

So, if the input matrix is like:

7 2 6
3 7 2
5 3 7

Then the output will be True because each diagonal has consistent values.

Algorithm

To check if a matrix is Toeplitz, we follow these steps:

  • For each row i except the last one, do:
    • For each column j except the last one, do:
      • If matrix[i][j] is not same as matrix[i+1][j+1], then return False
  • Return True if all diagonal elements match

Implementation Using Class Method

Here's the implementation using a class-based approach ?

class Solution:
    def solve(self, matrix):
        for i in range(len(matrix) - 1):
            for j in range(len(matrix[0]) - 1):
                if matrix[i][j] != matrix[i + 1][j + 1]:
                    return False
        return True

# Test the solution
ob = Solution()
matrix = [[7, 2, 6], [3, 7, 2], [5, 3, 7]]
print(ob.solve(matrix))
True

Simple Function Approach

You can also implement this using a simple function ?

def is_toeplitz(matrix):
    rows, cols = len(matrix), len(matrix[0])
    
    for i in range(rows - 1):
        for j in range(cols - 1):
            if matrix[i][j] != matrix[i + 1][j + 1]:
                return False
    return True

# Test with different matrices
matrix1 = [[7, 2, 6], [3, 7, 2], [5, 3, 7]]
matrix2 = [[1, 2, 3], [4, 1, 2], [7, 4, 1]]

print("Matrix 1 is Toeplitz:", is_toeplitz(matrix1))
print("Matrix 2 is Toeplitz:", is_toeplitz(matrix2))
Matrix 1 is Toeplitz: True
Matrix 2 is Toeplitz: True

How It Works

The algorithm compares each element with the element diagonally below and to the right. If any pair doesn't match, the matrix is not Toeplitz. The nested loops ensure we check all necessary diagonal relationships without going out of bounds.

Toeplitz Matrix Check 7 2 6 3 7 2 5 3 7 Same color = Same diagonal Red arrows show comparison direction

Conclusion

A Toeplitz matrix has identical values along each diagonal from top-left to bottom-right. The algorithm efficiently checks this by comparing each element with its diagonal neighbor in O(m×n) time complexity.

Updated on: 2026-03-25T10:37:21+05:30

788 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements