easy +10 pts

Toeplitz Matrix Check

Verify that every diagonal from top-left to bottom-right holds the same value throughout a 2D grid.

A matrix is called a **Toeplitz matrix** if every diagonal from the top-left to the bottom-right has the same element. In other words, for each cell, its value must equal the value of the cell that is diagonally down-right from it (if such a cell exists). Write a function `is_toeplitz(matrix)` that takes a non-empty 2D list of integers (all rows have the same length) and returns `True` if the matrix is Toeplitz, and `False` otherwise. The matrix can be rectangular (rows may not equal columns), but it will contain at least one row and at least one column. You must check the property as defined, not just adjacent diagonals — but note that checking all adjacent down-right pairs is equivalent. Your implementation should handle rectangular matrices correctly.

Constraints

- The matrix is a non-empty 2D list: `len(matrix) >= 1` and `len(matrix[0]) >= 1`. - All rows have the same length. - Elements are integers (but the logic works for any comparable type). - Time complexity should be O(rows × cols).

Example

>>> is_toeplitz([[1,2,3,4], [5,1,2,3], [9,5,1,2]])
True
>>> is_toeplitz([[1,2], [2,2]])
False
>>> is_toeplitz([[42]])
True
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compare each element with the one diagonally below-right: matrix[r][c] == matrix[r-1][c-1] (or the other direction).
Iterate from row 1 and column 1 onward to avoid out-of-bounds.
If any comparison fails, return False immediately; otherwise True.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.