A matrix is called Toeplitz if every diagonal from top-left to bottom-right has the same elements.
Given an m x n
matrix matrix
, return true
if the matrix is Toeplitz. Otherwise, return false
.
You need to implement the following function:
public boolean isToeplitzMatrix(int[][] matrix);
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.
Input:
matrix = [
[1,2],
[2,2]
]
Output: false
Explanation:
The bottom left value is different from the top right value in the diagonal starting from matrix[1][0].
To determine if a matrix is Toeplitz, we need to check if every diagonal from top-left to bottom-right has the same elements. Specifically, for each element at matrix[i][j]
, we need to ensure that matrix[i][j] == matrix[i+1][j+1]
(provided i+1
and j+1
are within bounds).
matrix[i+1][j+1]
to compare.matrix[i][j]
, verify that it is equal to matrix[i+1][j+1]
.false
.true
.public class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
// Iterate over each element except for the last row and last column
for (int i = 0; i < matrix.length - 1; i++) {
for (int j = 0; j < matrix[0].length - 1; j++) {
// Check if the current element is equal to the element diagonally below it
if (matrix[i][j] != matrix[i + 1][j + 1]) {
return false;
}
}
}
return true;
}
}
The time complexity of this solution is 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 of the matrix once.
The space complexity is O(1) since we are using a constant amount of extra space.
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?