A matrix is called Toeplitz if every diagonal from top-left to bottom-right has the same elements. Now given an m x n
matrix, return True
if the matrix is Toeplitz. Otherwise, return False
.
A matrix can be defined as a two-dimensional array.
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation: In the given matrix, each diagonal from top-left to bottom-right has the same elements.
Input:
matrix = [
[1,2],
[2,2]
]
Output: False
Explanation: The diagonal starting at (0,0) contains 1 and 2 which are different.
True
because there are no elements to form a conflicting diagonal.To determine whether the given matrix is a Toeplitz matrix, we need to ensure that each element in the matrix is equal to the element diagonally before it. Specifically, for every element at position (i, j)
, it must hold that matrix[i][j] == matrix[i-1][j-1]
if both i-1
and j-1
are within the matrix bounds.
(i, j)
, check if it is equal to the element at (i-1, j-1)
.False
.True
.def isToeplitzMatrix(matrix):
if not matrix or not matrix[0]:
return True
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
True
.i=1
and j=1
because the first row and column do not need to be checked.(i, j)
, we compare it with its top-left diagonal neighbor (i-1, j-1)
.False
. If all checks pass, we return True
.O(m * n)
, where m
is the number of rows and n
is the number of columns in the matrix. This is because we are iterating through each element in the matrix once.O(1)
, since we are only using a constant amount of extra space for our variables.This algorithm efficiently verifies if the given matrix is Toeplitz by leveraging direct element comparison based on their indices within the bounds of the matrix.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?