Problem overview
The function isToeplitzMatrix receives matrix, a list of m rows of n integers. It returns True when every diagonal holds a single value and False otherwise. A diagonal starts in the top row or in the left column and goes one row down and one column right at each step.
In [[7, 3, 8], [4, 7, 3], [6, 4, 7], [1, 6, 4]] the diagonals hold 1; 6, 6; 4, 4, 4; 7, 7, 7; 3, 3; and 8, so the answer is True. In [[5, 2, 9, 1], [0, 5, 2, 9], [3, 0, 5, 8]] the diagonal that starts at the 2 in row 0 holds 2, 2, 8, and the 8 breaks the pattern, so the answer is False. A grid with one column has only one-cell diagonals, so it is always True.
The statement asks for O(m * n) time and O(1) extra space.
Approach: every cell must equal the cell before it on its diagonal
One could collect each diagonal into a list and check that its values are all equal. That works, but it uses extra memory and needs code to find where each diagonal starts.
A local rule is enough. Each cell not in the top row or left column has exactly one predecessor on its diagonal: the cell up and to the left, matrix[i - 1][j - 1]. If every cell equals its predecessor, then along any diagonal each value equals the one before it, so the whole diagonal repeats the value of its first cell. If some cell differs from its predecessor, that diagonal has two different values, and the answer is False right away.
The cells in row 0 and column 0 have no predecessor. They are the starts of diagonals, and nothing needs to be checked for them.
Step by step
- Read the sizes:
m = len(matrix)rows andn = len(matrix[0])columns, taken from the first row since all rows have the same length. - Loop over the rows from 1.
range(1, m)skips row 0, whose cells only start diagonals. The end of arangeis excluded, soistops atm - 1. - Loop over the columns from 1.
range(1, n)skips column 0 for the same reason. The two loops together reach every cell that has an up-left neighbor, once each. - Compare with the predecessor. If
matrix[i][j]differs frommatrix[i - 1][j - 1], returnFalse. One mismatch settles the answer, so there is no need to look further. - Return
Trueonce the loops finish: no cell disagreed with its predecessor.
The solution in Python
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
m = len(matrix)
n = len(matrix[0])
for i in range(1, m):
for j in range(1, n):
if matrix[i][j] != matrix[i - 1][j - 1]:
return False
return True
Both loops start at 1 because of a Python detail: negative indexes are legal and count from the end. If a loop started at 0, matrix[i - 1][j - 1] with i = 0 would silently read the last row instead of failing, and the function would compare cells that are not neighbors. On the first example that mistake makes the function answer False for a grid that is Toeplitz. Starting at 1 avoids the problem completely.
Complexity
Time is O(m * n): each cell below row 0 and right of column 0 is compared once. Space is O(1): the function stores only m, n and the two loop counters, and never copies a row or a diagonal.
Edge cases and common mistakes
- One row or one column. With
[[1, 2, 3, 4]]the outer loop isrange(1, 1), which is empty, so the function returnsTrue. That is right: each diagonal is a single cell. The same holds for[[3], [8], [3]], where the inner loop is empty. - Comparing the wrong neighbor. Comparing with
matrix[i - 1][j](directly above) ormatrix[i][j - 1](to the left) checks rows or columns, not diagonals. - Only checking the main diagonal. The rule applies to every diagonal, which is why every cell is checked.
- Going the other way. Comparing
matrix[i][j]with the down-right cell is also correct, but then the loops must stop one row and one column early, or the index runs off the grid.
Testing
The three examples give True, False and True. A one-row grid such as [[1, 2, 3, 4]] also gives True. When you write your own tests, make the one bad cell sit in the last row or last column, so that a loop that stops too early is caught.
