← Questions

Toeplitz matrix: check that every diagonal holds one value

0
MetaCodingLast asked Aug 2025

Two checks on the diagonals of a matrix. First decide whether every cell on the main diagonal of a square matrix holds the same value. Then decide whether the matrix is Toeplitz: every diagonal running from top-left to bottom-right holds a single repeated value.

Part 1: identical main diagonal

Unless you agree on a different interface with the interviewer, assume:

  • same_main_diagonal(matrix: list[list[int]]) -> bool — True when every matrix[i][i] is equal. An empty matrix returns True.
same_main_diagonal([[5, 1, 2], [3, 5, 4], [6, 7, 5]])  ->  True    # 5, 5, 5
same_main_diagonal([[5, 1, 2], [3, 9, 4], [6, 7, 5]])  ->  False   # 5, 9, 5

Part 2: Toeplitz matrix

  • is_toeplitz(matrix: list[list[int]]) -> bool — the matrix may be rectangular. True when every cell equals the cell up and to its left, wherever that cell exists.
is_toeplitz([[1, 2, 3, 4],
             [5, 1, 2, 3],
             [9, 5, 1, 2]])  ->  True    # diagonals 9 | 5,5 | 1,1,1 | 2,2,2 | 3,3 | 4
is_toeplitz([[1, 2],
             [2, 2]])        ->  False   # the main diagonal holds 1 and 2

Constraints

  • Up to 1000 x 1000 cells; values in [-10^9, 10^9].
  • Part 1 matrices are square; Part 2 matrices are rectangular with rows of equal length.

Clarifying questions

  • Is the matrix square, and can it be empty?
  • For Part 2, can rows have different lengths?
  • Do I return early on the first mismatch?

What a strong answer covers

  • Part 1: compare each matrix[i][i] with matrix[0][0]; O(n) time, never touching off-diagonal cells.
  • Part 2: compare each matrix[i][j] with matrix[i-1][j-1] for i, j >= 1; O(m * n) time, O(1) space.
  • Why the neighbour comparison is enough: equality chains along each diagonal.
  • Edge cases: empty matrix, one row, one column.

Follow-ups

  • The matrix is too large for memory and you can load only one row at a time. Compare each row with the previous one shifted by one.
  • You can load only part of a row at a time.
  • Check the anti-diagonals (top-right to bottom-left) instead.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding