Toeplitz Matrix
Easy matrix
Description
Constraints
1 <= rows, cols <= 1000
Examples
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
Hints (1)
- Compare each cell with the one above and to the left.
Solutions
Compare with the up-left neighbour. · Time O(rows*cols) · Space O(1)
func isToeplitzMatrix(matrix [][]int) bool {
for r := 1; r < len(matrix); r++ {
for c := 1; c < len(matrix[0]); c++ {
if matrix[r][c] != matrix[r-1][c-1] {
return false
}
}
}
return true
}
Compare with the up-left neighbour. · Time O(rows*cols) · Space O(1)
function isToeplitzMatrix(matrix) {
for (let r = 1; r < matrix.length; r++) {
for (let c = 1; c < matrix[0].length; c++) {
if (matrix[r][c] !== matrix[r - 1][c - 1]) return false;
}
}
return true;
}
Compare with the up-left neighbour. · Time O(rows*cols) · Space O(1)
function isToeplitzMatrix($matrix) {
for ($r = 1; $r < count($matrix); $r++) {
for ($c = 1; $c < count($matrix[0]); $c++) {
if ($matrix[$r][$c] !== $matrix[$r - 1][$c - 1]) { return false; }
}
}
return true;
}
Compare with the up-left neighbour. · Time O(rows*cols) · Space O(1)
def isToeplitzMatrix(matrix):
for r in range(1, len(matrix)):
for c in range(1, len(matrix[0])):
if matrix[r][c] != matrix[r - 1][c - 1]:
return False
return True
Compare with the up-left neighbour. · Time O(rows*cols) · Space O(1)
function isToeplitzMatrix(matrix: number[][]): boolean {
for (let r = 1; r < matrix.length; r++) {
for (let c = 1; c < matrix[0].length; c++) {
if (matrix[r][c] !== matrix[r - 1][c - 1]) return false;
}
}
return true;
}
Create a free account to submit solutions, track progress and save problems.
Create account