Sponsored
Sponsored
This method involves checking each element of the matrix to ensure that it equals the element diagonally ahead of it - that is, for each cell matrix[i][j]
, it should be equal to matrix[i+1][j+1]
, provided both indices are within bounds.
Time Complexity: O(m * n) where m
is the number of rows and n
is the number of columns.
Space Complexity: O(1), since no additional data structures are used.
1function isToeplitzMatrix(matrix) {
2 for (let i = 0; i < matrix.length - 1; i++) {
3 for (let j = 0; j < matrix[0].length - 1; j++) {
4 if (matrix[i][j] !== matrix[i + 1][j + 1]) {
5 return false;
6 }
7 }
8 }
9 return true;
10}
JavaScript implementation uses nested for
loops to check each element against its diagonal successor.
We can use a HashMap (or dictionary) to maintain the first element of each diagonal. Each key represents the difference between row and column indices, and the value is the first element at this diagonal. While iterating, if a new element violates this rule, the matrix isn't Toeplitz.
Time Complexity: O(m * n)
Space Complexity: O(m + n) for storing diagonal mappings.
1import java.util.HashMap;
2
3
In Java, we utilize a HashMap
to store the first element of each diagonal and compare subsequent diagonal elements against this element. Each diagonal is identified by the difference between its row and column indices.