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.
1def isToeplitzMatrix(matrix):
2 for i in range(len(matrix) - 1):
3 for j in range(len(matrix[0]) - 1):
4 if matrix[i][j] != matrix[i + 1][j + 1]:
5 return False
6 return True
This Python solution similarly traverses the matrix and compares each element to its diagonal successor. If any mismatch is found, it returns False
.
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.
1import java.util.HashMap;
2
3
In Java, we utilize a HashMap
to store the first element of each diagonal and compare subsequent diagonal elements against this element. Each diagonal is identified by the difference between its row and column indices.