[
2d-array
]
Leetcode 0766 Toeplitz Matrix
Problem statement
https://leetcode.com/problems/toeplitz-matrix/
Solution
Just iterate line by line and check that next line elements starting from first equal to current line elements except last one.
Complexity
Time complexity is O(mn), space is O(n).
Code
class Solution:
def isToeplitzMatrix(self, matrix):
m, n = len(matrix), len(matrix[0])
row = matrix[0]
for i in range(1, m):
if matrix[i][1:] != row[:-1]: return False
row = matrix[i]
return True
Remark
We also can do it in O(1) space if we check for each element its top left neighbor.