Start learning free

LESSON 332 OF 673 · MATRIX

Toeplitz Matrix in Python: Compare Each Cell to Its Up-Left Neighbor

Practice O(m · n) Read the full explanation

You get a grid of integers, matrix, with m rows and n columns.

Return True if each diagonal of the grid holds a single value. Otherwise, return False.

A diagonal starts in the top row or the left column. From there, each step goes one row down and one column right. A grid like that is called a Toeplitz matrix.

The grid is a list of rows. Each row is a list of integers. Rows are counted from 0 at the top, columns from 0 at the left.

 

Example 1:

Input: matrix = [
  [7, 3, 8],
  [4, 7, 3],
  [6, 4, 7],
  [1, 6, 4]
]
Output: True
Explanation: The grid has six diagonals.
From the bottom-left to the top-right, they hold:
1
6, 6
4, 4, 4
7, 7, 7
3, 3
8
Each one repeats a single value.

Example 2:

Input: matrix = [
  [5, 2, 9, 1],
  [0, 5, 2, 9],
  [3, 0, 5, 8]
]
Output: False
Explanation: Start at the 2 in row 0.
Its diagonal holds 2, 2 and 8.
The 8 breaks the pattern.
All the other diagonals are fine.

Example 3:

Input: matrix = [
  [3],
  [8],
  [3]
]
Output: True
Explanation: The grid has one column.
So each diagonal is a single cell.

 

Constraints:

  • 1 to 500 rows.
  • 1 to 500 columns.
  • All rows have the same length.
  • Each value is a whole number from 0 to 99.

Note:

Your solution should run in O(m * n) time and use O(1) extra space.

STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · MATRIX

    Toeplitz Matrix in Python, explained

    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

    1. Read the sizes: m = len(matrix) rows and n = len(matrix[0]) columns, taken from the first row since all rows have the same length.
    2. Loop over the rows from 1. range(1, m) skips row 0, whose cells only start diagonals. The end of a range is excluded, so i stops at m - 1.
    3. 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.
    4. Compare with the predecessor. If matrix[i][j] differs from matrix[i - 1][j - 1], return False. One mismatch settles the answer, so there is no need to look further.
    5. Return True once 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 is range(1, 1), which is empty, so the function returns True. 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) or matrix[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.

    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free