class Solution:
def isToeplitzMatrix(self, matrix):
rows = len(matrix)
cols = 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
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
for (int i = 1; i < rows; ++i) {
for (int j = 1; j < cols; ++j) {
if (matrix[i][j] != matrix[i-1][j-1]) {
return false;
}
}
}
return true;
}
};
class Solution {
public boolean isToeplitzMatrix(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] != matrix[i-1][j-1]) {
return false;
}
}
}
return true;
}
}
var isToeplitzMatrix = function(matrix) {
let rows = matrix.length, cols = matrix[0].length;
for (let i = 1; i < rows; i++) {
for (let j = 1; j < cols; j++) {
if (matrix[i][j] !== matrix[i-1][j-1]) {
return false;
}
}
}
return true;
};
Given a 2D array matrix
, determine if it is a Toeplitz matrix. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. In other words, for all valid i
and j
, matrix[i][j] == matrix[i-1][j-1]
whenever i > 0
and j > 0
.
matrix
with at least 1 row and 1 column.true
if matrix
is Toeplitz, false
otherwise.
The core idea is to verify that every diagonal (from top-left to bottom-right) has the same value. A brute-force approach might involve collecting all diagonals and checking their values, but that's unnecessary. Instead, we can observe that for any cell (i, j)
(except those in the first row or first column), its value should match the value in the cell directly up-and-left, i.e., (i-1, j-1)
. If we find any mismatch, the matrix is not Toeplitz.
This insight allows us to avoid extra data structures or diagonal tracking. We just compare each cell (except those in the first row or column) with its top-left neighbor.
Here’s how we can solve the problem efficiently:
i = 1
and j = 1
to avoid the first row and column (which have no upper-left neighbors).(i, j)
, compare matrix[i][j]
with matrix[i-1][j-1]
.false
.true
at the end.This approach is efficient because:
Example:
Input:
matrix = [ [1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2] ]
true
.
Counter-example:
Input:
matrix = [ [1, 2], [2, 2] ]
false
.The Toeplitz Matrix problem is efficiently solved by simply comparing each cell to its top-left neighbor, leveraging the definition of a Toeplitz matrix. This approach is both intuitive and optimal, requiring only a double loop and no extra space. The key insight is that the property of all diagonals being equal can be checked locally, making the solution elegant and efficient.