← Questions
Toeplitz matrix: check that every diagonal holds one value
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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—Truewhen everymatrix[i][i]is equal. An empty matrix returnsTrue.
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.Truewhen 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 1000cells; 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]withmatrix[0][0];O(n)time, never touching off-diagonal cells. - Part 2: compare each
matrix[i][j]withmatrix[i-1][j-1]fori, 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.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
