An element matrix[i][j] belongs to the same diagonal as matrix[i-1][j-1]. We just need to check if each element is equal to its top-left neighbor.
- Iterate through
ifrom 1 tom-1. - Iterate through
jfrom 1 ton-1. - If
matrix[i][j] != matrix[i-1][j-1], return False. - If loop finishes, return True.
- Time Complexity: O(M * N).
- Space Complexity: O(1).
def is_toeplitz_matrix(matrix):
for i in range(1, len(matrix)):
for j in range(1, len(matrix[0])):
if matrix[i][j] != matrix[i - 1][j - 1]:
return False
return True