Find if given matrix is Toeplitz or not
Last Updated :
02 May, 2025
Given a square matrix mat[][] of order n, your task is to 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 son on.
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
The idea is to 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()
. - For each column index
i
from 0
to m - 1
, call checkDiagonal(mat, 0, i)
; if it returns false, immediately return false from isToeplitz
. - For each row index
i
from 0
to n - 1
, call checkDiagonal(mat, i, 0)
; if it returns false, immediately return false from isToeplitz
. - 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.
Below is given the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// function to check if diagonal elements are same
bool checkDiagonal(vector<vector<int>> &mat, int x, int y) {
int n = mat.size(), m = mat[0].size();
for(int i = x + 1, j = y + 1;
i < n && j < m; i++, j++) {
if(mat[i][j] != mat[x][y])
return false;
}
return true;
}
// Function to check whether given
// matrix is toeplitz matrix or not
bool isToeplitz(vector<vector<int>> &mat) {
int n = mat.size(), m = mat[0].size();
// check each descending diagonal starting from
// first row and first column of the matrix
for(int i = 0; i < m; i++)
if(!checkDiagonal(mat, 0, i))
return false;
for(int i = 0; i < n; i++)
if(!checkDiagonal(mat, i, 0))
return false;
// if all diagonals are same, return true
return true;
}
int main() {
vector<vector<int>> mat = {
{6, 7, 8},
{4, 6, 7},
{1, 4, 6}
};
if(isToeplitz(mat)) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
Java
import java.util.*;
class GfG {
// function to check if diagonal elements are same
static boolean checkDiagonal(List<List<Integer>> mat, int x, int y) {
int n = mat.size(), m = mat.get(0).size();
for(int i = x + 1, j = y + 1;
i < n && j < m; i++, j++) {
if(!mat.get(i).get(j).equals(mat.get(x).get(y)))
return false;
}
return true;
}
// Function to check whether given
// matrix is toeplitz matrix or not
static boolean isToeplitz(List<List<Integer>> mat) {
int n = mat.size(), m = mat.get(0).size();
// check each descending diagonal starting from
// first row and first column of the matrix
for(int i = 0; i < m; i++)
if(!checkDiagonal(mat, 0, i))
return false;
for(int i = 0; i < n; i++)
if(!checkDiagonal(mat, i, 0))
return false;
// if all diagonals are same, return true
return true;
}
public static void main(String[] args) {
List<List<Integer>> mat = Arrays.asList(
Arrays.asList(6, 7, 8),
Arrays.asList(4, 6, 7),
Arrays.asList(1, 4, 6)
);
if(isToeplitz(mat)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python
# function to check if diagonal elements are same
def checkDiagonal(mat, x, y):
n, m = len(mat), len(mat[0])
i, j = x + 1, y + 1
while i < n and j < m:
if mat[i][j] != mat[x][y]:
return False
i += 1
j += 1
return True
# Function to check whether given
# matrix is toeplitz matrix or not
def isToeplitz(mat):
n, m = len(mat), len(mat[0])
# check each descending diagonal starting from
# first row and first column of the matrix
for i in range(m):
if not checkDiagonal(mat, 0, i):
return False
for i in range(n):
if not checkDiagonal(mat, i, 0):
return False
# if all diagonals are same, return true
return True
mat = [
[6, 7, 8],
[4, 6, 7],
[1, 4, 6]
]
if isToeplitz(mat):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
class GfG {
// function to check if diagonal elements are same
static bool checkDiagonal(List<List<int>> mat, int x, int y) {
int n = mat.Count, m = mat[0].Count;
for(int i = x + 1, j = y + 1;
i < n && j < m; i++, j++) {
if(mat[i][j] != mat[x][y])
return false;
}
return true;
}
// Function to check whether given
// matrix is toeplitz matrix or not
static bool isToeplitz(List<List<int>> mat) {
int n = mat.Count, m = mat[0].Count;
// check each descending diagonal starting from
// first row and first column of the matrix
for(int i = 0; i < m; i++)
if(!checkDiagonal(mat, 0, i))
return false;
for(int i = 0; i < n; i++)
if(!checkDiagonal(mat, i, 0))
return false;
// if all diagonals are same, return true
return true;
}
static void Main() {
var mat = new List<List<int>> {
new List<int> {6, 7, 8},
new List<int> {4, 6, 7},
new List<int> {1, 4, 6}
};
if(isToeplitz(mat)) {
Console.WriteLine("Yes");
} else {
Console.WriteLine("No");
}
}
}
JavaScript
// function to check if diagonal elements are same
function checkDiagonal(mat, x, y) {
let n = mat.length, m = mat[0].length;
for(let i = x + 1, j = y + 1;
i < n && j < m; i++, j++) {
if(mat[i][j] !== mat[x][y])
return false;
}
return true;
}
// Function to check whether given
// matrix is toeplitz matrix or not
function isToeplitz(mat) {
let n = mat.length, m = mat[0].length;
// check each descending diagonal starting from
// first row and first column of the matrix
for(let i = 0; i < m; i++)
if(!checkDiagonal(mat, 0, i))
return false;
for(let i = 0; i < n; i++)
if(!checkDiagonal(mat, i, 0))
return false;
// if all diagonals are same, return true
return true;
}
let mat = [
[6, 7, 8],
[4, 6, 7],
[1, 4, 6]
];
if(isToeplitz(mat)) {
console.log("Yes");
} else {
console.log("No");
}
[Expected Approach - 2] - Checking Diagonally Above Element - O(n * n) Time and O(1) Space
The idea is to scan every cell from the second row and second column onward, comparing each value to its top-left neighbor. If any element differs from the one diagonally above it, you’ve found a violation of the Toeplitz property and can stop immediately; if you make it through the entire matrix without mismatch, every diagonal is 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
.
Below is given the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check whether given
// matrix is toeplitz matrix or not
bool isToeplitz(vector<vector<int>> &mat) {
int n = mat.size(), m = mat[0].size();
// check diagonally above element of
// each element in the matrix
for(int i = 1; i < n; i++) {
for(int j = 1; j < m; j++) {
if(mat[i][j] != mat[i - 1][j - 1])
return false;
}
}
// if all diagonals are same, return true
return true;
}
int main() {
vector<vector<int>> mat = {
{6, 7, 8},
{4, 6, 7},
{1, 4, 6}
};
if(isToeplitz(mat)) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
Java
import java.util.*;
class GfG {
// Function to check whether given
// matrix is toeplitz matrix or not
static boolean isToeplitz(List<List<Integer>> mat) {
int n = mat.size(), m = mat.get(0).size();
// check diagonally above element of
// each element in the matrix
for(int i = 1; i < n; i++) {
for(int j = 1; j < m; j++) {
if(mat.get(i).get(j) != mat.get(i - 1).get(j - 1))
return false;
}
}
// if all diagonals are same, return true
return true;
}
public static void main(String[] args) {
List<List<Integer>> mat = Arrays.asList(
Arrays.asList(6, 7, 8),
Arrays.asList(4, 6, 7),
Arrays.asList(1, 4, 6)
);
if(isToeplitz(mat)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python
# Function to check whether given
# matrix is toeplitz matrix or not
def isToeplitz(mat):
n, m = len(mat), len(mat[0])
# check diagonally above element of
# each element in the matrix
for i in range(1, n):
for j in range(1, m):
if mat[i][j] != mat[i - 1][j - 1]:
return False
# if all diagonals are same, return true
return True
mat = [
[6, 7, 8],
[4, 6, 7],
[1, 4, 6]
]
if isToeplitz(mat):
print("Yes")
else:
print("No")
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to check whether given
// matrix is toeplitz matrix or not
static bool isToeplitz(List<List<int>> mat) {
int n = mat.Count, m = mat[0].Count;
// check diagonally above element of
// each element in the matrix
for(int i = 1; i < n; i++) {
for(int j = 1; j < m; j++) {
if(mat[i][j] != mat[i - 1][j - 1])
return false;
}
}
// if all diagonals are same, return true
return true;
}
static void Main() {
var mat = new List<List<int>> {
new List<int> {6, 7, 8},
new List<int> {4, 6, 7},
new List<int> {1, 4, 6}
};
if(isToeplitz(mat)) {
Console.WriteLine("Yes");
} else {
Console.WriteLine("No");
}
}
}
JavaScript
// Function to check whether given
// matrix is toeplitz matrix or not
function isToeplitz(mat) {
let n = mat.length, m = mat[0].length;
// check diagonally above element of
// each element in the matrix
for(let i = 1; i < n; i++) {
for(let j = 1; j < m; j++) {
if(mat[i][j] !== mat[i - 1][j - 1])
return false;
}
}
// if all diagonals are same, return true
return true;
}
let mat = [
[6, 7, 8],
[4, 6, 7],
[1, 4, 6]
];
if(isToeplitz(mat)) {
console.log("Yes");
} else {
console.log("No");
}
[Alternate Approach] - Using Hashing - O(n * n) Time and O(n) Space
The idea is to assign a unique identifier to each down‑right diagonal (the row index minus the column index) and use a hash map to record the first value seen for that diagonal. As you scan the entire matrix, you compute this key for each cell and either verify it matches the stored value or, if it’s new, store it. A single mismatch lets you bail out with false; otherwise you conclude true at the end.
Follow the below given steps:
- Determine the matrix dimensions (row count and column count) from
mat
. - Create an empty hashmap
mp
to map each diagonal key to its representative value. - Walk through every cell in
mat
by its row index i
and column index j
. - For each cell, form the diagonal key by subtracting
j
from i
. - If
mp
already holds this key, compare the current element to the stored value; if they differ, return false immediately. - If the key is not yet in
mp
, record the current element under that key. - If you complete the traversal without any mismatch, return true.
Illustration:
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.

For red-coloured diagonal, difference is 3. For green-coloured diagonal, difference is 0. For orange-coloured diagonal, difference is -2 and so on...
Below is given the implementation:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to check whether given
// matrix is toeplitz matrix or not
bool isToeplitz(vector<vector<int>> &mat) {
int n = mat.size(), m = mat[0].size();
// HashMap to store key,value pairs
unordered_map<int, int> mp;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int key = i - j;
// If key value exists in the hashmap,
if (mp[key]) {
// check if the value is same
// as the current element
if (mp[key] != mat[i][j])
return false;
}
// Else we put key,value pair in hashmap
else {
mp[i - j] = mat[i][j];
}
}
}
return true;
}
int main() {
vector<vector<int>> mat = {
{6, 7, 8},
{4, 6, 7},
{1, 4, 6}
};
if(isToeplitz(mat)) {
cout << "Yes";
} else {
cout << "No";
}
return 0;
}
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);
}
}
Python
# 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#
using System;
using System.Collections.Generic;
class GfG {
// Function to check whether given
// matrix is toeplitz matrix or not
static bool isToeplitz(List<List<int>> mat) {
int n = mat.Count, m = mat[0].Count;
// HashMap to store key,value pairs
Dictionary<int,int> mp = new Dictionary<int,int>();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int key = i - j;
// If key value exists in the hashmap,
if (mp.ContainsKey(key)) {
// check if the value is same
// as the current element
if (mp[key] != mat[i][j])
return false;
}
// Else we put key,value pair in hashmap
else {
mp[i - j] = mat[i][j];
}
}
}
return true;
}
static void Main() {
var mat = new List<List<int>> {
new List<int> {6, 7, 8},
new List<int> {4, 6, 7},
new List<int> {1, 4, 6}
};
if(isToeplitz(mat)) {
Console.WriteLine("Yes");
} else {
Console.WriteLine("No");
}
}
}
JavaScript
// Function to check whether given
// matrix is toeplitz matrix or not
function isToeplitz(mat) {
let n = mat.length, m = mat[0].length;
// HashMap to store key,value pairs
const mp = new Map();
for(let i = 0; i < n; i++) {
for(let j = 0; j < m; j++) {
let key = i - j;
// If key value exists in the hashmap,
if (mp.has(key)) {
// check if the value is same
// as the current element
if (mp.get(key) !== mat[i][j])
return false;
}
// Else we put key,value pair in hashmap
else {
mp.set(i - j, mat[i][j]);
}
}
}
return true;
}
let mat = [
[6, 7, 8],
[4, 6, 7],
[1, 4, 6]
];
if(isToeplitz(mat)) {
console.log("Yes");
} else {
console.log("No");
}
PROBLEM OF THE DAY : 27/06/2024 | Toeplitz Matrix
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem