Toeplitz Matrix

Given an `m x n` matrix, return `true` if the matrix is Toeplitz, otherwise return `false`. A matrix is Toeplitz when every diagonal running from top-left to bottom-right holds a single repeated value.

30:00

Toeplitz Matrix
easy
Free written solution
Topics
Companies

Given an m x n matrix, return true if the matrix is Toeplitz, otherwise return false.

A matrix is Toeplitz when every diagonal running from top-left to bottom-right holds a single repeated value.

Example 1:
Input: {"matrix":[[1,2,3,4],[5,1,2,3],[9,5,1,2]]}
Output: true
Constraints:
  • m==matrix.lengthm == \text{matrix.length}

  • n==matrix[i].lengthn == \text{matrix}[i].\text{length}

  • 1≤m,n≤201 \leq m, n \leq 20

  • 0≤matrix[i][j]≤990 \leq \text{matrix}[i][j] \leq 99

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"matrix":[[1,2,3,4],[5,1,2,3],[9,5,1,2]]}

The matrix has 6 top-left to bottom-right diagonals. Instead of walking each diagonal, compare every cell with its upper-left neighbour: if all those pairs match, every diagonal is constant.

matrix[r][c] == matrix[r-1][c-1] ?

1
2
3
4
5
1
2
3
9
5
1
2

Each colour is one diagonal (constant c - r). A ✓ means the cell matched the cell up and to its left; the gold link joins the pair being compared.

Variables
VariableValue
m3
n4
DepthFunction Call
Stack empty
0/9