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.
1class Solution {
2 public boolean isToeplitzMatrix(int[][] matrix) {
3 for (int i = 0; i < matrix.length - 1; i++) {
4 for (int j = 0; j < matrix[i].length - 1; j++) {
5 if (matrix[i][j] != matrix[i + 1][j + 1]) {
6 return false;
7 }
8 }
9 }
10 return true;
11 }
12}
In Java, we iterate through the 2D-array matrix, ensuring each cell matches its diagonal successor. We stop and return false
as soon as a mismatch is detected.
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.