You get a grid of numbers, matrix, with m rows and n columns. Call it Toeplitz when every diagonal running from upper left to lower right holds one repeated value.
Return true if matrix is Toeplitz and false if any of those diagonals mixes two different values.
Example 1
Input: matrix = [[7, 3, 8, 6],
[0, 7, 3, 8],
[4, 0, 7, 3]]
Output: true
Why: each diagonal repeats one value: 4 | 0 0 | 7 7 7 | 3 3 3 | 8 8 | 62 more examples and the constraints
Example 2
Input: matrix = [[5, 6], [6, 1]] Output: false Why: the main diagonal holds 5 and then 1
Example 3
Input: matrix = [[2, 9, 9]] Output: true Why: with one row, every diagonal is a single cell
Constraints
- The grid has between 1 and 20 rows, and between 1 and 20 columns
- Every value is a whole number from 0 to 99
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Group by diagonal keyO(m·n)
- Compare with the top-left neighbourO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 20 × 20 matrix | Verdict |
|---|---|---|---|
| Group by diagonal key | O(m·n) | Clear; uses a map | |
| Compare with the top-left neighbour | O(m·n) | Best; no extra memory |
m = rows, n = columns. Both read each cell once; the map adds hashing and memory.
Edge cases to test
- One row or one column. Every diagonal has a single cell, so the answer is always true.
- A single cell. [[4]] is true.
- Mismatch in the last cell. The check must reach the bottom-right corner before saying true.
- Same numbers, wrong direction. [[1, 2], [1, 2]] is false: the equal values run down columns, not along diagonals.
Common mistakes
- Starting the loops at 0 and reading
matrix[-1], which wraps around in Python and crashes elsewhere. - Checking the anti-diagonals (top-right to bottom-left) instead.
- Using the row count for both loop bounds on a matrix that is not square.
How to talk through it
- 1Clarify. Which diagonal direction? Can the matrix be a single row or column?
- 2Give the first idea. Cells on one diagonal share r − c; group by that key and compare with a map.
- 3Simplify. Equal to the top-left neighbour everywhere means each diagonal is constant, with no map.
- 4Code the double loop. Start both indices at 1 and return false on the first mismatch.
- 5Test out loud. Run a single row, a single column and a mismatch in the last cell before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?