Sponsored
Sponsored
This method involves checking each element of the matrix to ensure that it equals the element diagonally ahead of it - that is, for each cell matrix[i][j]
, it should be equal to matrix[i+1][j+1]
, provided both indices are within bounds.
Time Complexity: O(m * n) where m
is the number of rows and n
is the number of columns.
Space Complexity: O(1), since no additional data structures are used.
1public class Solution {
2 public bool IsToeplitzMatrix(int[][] matrix) {
3 for (int i = 0; i < matrix.Length - 1; i++) {
4 for (int j = 0; j < matrix[i].Length - 1; j++) {
5 if (matrix[i][j] != matrix[i + 1][j + 1]) {
6 return false;
7 }
8 }
9 }
10 return true;
11 }
12}
In C#, the matrix is an array of arrays. We use straightforward nested loops to compare each element with its diagonal counterpart.
We can use a HashMap (or dictionary) to maintain the first element of each diagonal. Each key represents the difference between row and column indices, and the value is the first element at this diagonal. While iterating, if a new element violates this rule, the matrix isn't Toeplitz.
Time Complexity: O(m * n)
Space Complexity: O(m + n) for storing diagonal mappings.
1def isToeplitzMatrix(matrix):
2 diagonal_map = {
In this Python implementation, a dictionary keeps track of each diagonal. The key (i - j)
refers to a specific diagonal, and its value is the element that should be the same for all elements in this diagonal.