Problem
Given an m x n
matrix
, return true
if the matrix is Toeplitz. Otherwise, return false
.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Examples
Example 1:
$$ \begin{bmatrix} 1 & 2 & 3 & 4 \\ 5 & 1 & 2 & 3 \\ 9 & 5 & 1 & 2 \end{bmatrix} $$
|
|
Example 2: $$ \begin{bmatrix} 1 & 2 \\ 2 & 2 \end{bmatrix} $$
|
|
Solution
Method 1 - Iteration
We can iterate through each element in the matrix (except the last row and last column) and checks if the current element matrix[i][j]
is equal to the element to its bottom-right diagonal matrix[i+1][j+1]
. If any elements do not match, it returns False
. If all elements match the condition, it returns True
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
, wherem
is the number of rows andn
is the number of columns in the matrix. The function iterates through nearly all elements of the matrix once. - 🧺 Space complexity:
O(1)
, The space complexity is constant because no additional space proportional to the input size is used. The function only uses a fixed amount of extra space for variablesi
andj
.