Given an m x n
matrix, determine if it is a Toeplitz matrix. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Explanation: In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]]
Output: false
Explanation: The diagonal "[1, 2]" has different elements.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
Could you implement a function to check if a given matrix is a Toeplitz matrix? Also, consider follow-up questions such as:
Given an m x n
matrix, determine if it is a Toeplitz matrix. A Toeplitz matrix has the property where each diagonal from top-left to bottom-right has the same elements.
The brute force solution involves iterating through each diagonal and checking if all elements in that diagonal are the same. This can be done by comparing each element with the first element of the diagonal.
false
. Otherwise, return true
.class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
rows, cols = len(matrix), len(matrix[0])
def check_diagonal(row_start, col_start):
value = matrix[row_start][col_start]
row, col = row_start, col_start
while row < rows and col < cols:
if matrix[row][col] != value:
return False
row += 1
col += 1
return True
# Check diagonals starting from the first column
for i in range(rows):
if not check_diagonal(i, 0):
return False
# Check diagonals starting from the first row (excluding the first element)
for j in range(1, cols):
if not check_diagonal(0, j):
return False
return True
O(m * n), where m
is the number of rows and n
is the number of columns.
O(1), as it uses constant extra space.
The optimal solution involves comparing each element with its top-left neighbor. If any element is different from its top-left neighbor, the matrix is not Toeplitz.
matrix[i-1][j-1]
.false
.true
.class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
rows, cols = len(matrix), len(matrix[0])
for i in range(1, rows):
for j in range(1, cols):
if matrix[i][j] != matrix[i-1][j-1]:
return False
return True
O(m * n), where m
is the number of rows and n
is the number of columns.
O(1), as it uses constant extra space.