Toeplitz Matrix (LeetCode 766): Solution and Explanation

Easy
Array
Matrix

Decide whether every top-left to bottom-right diagonal of an m x n matrix holds a single value. One comparison per cell, against the cell up and to the left, settles it.

Intuition

All cells on one top-left to bottom-right diagonal share the same c - r. You could group cells by that key and check each group, but there is a simpler local test.

A sequence is constant exactly when each element equals the one before it. On a diagonal, the element before (r, c) is (r - 1, c - 1). So if every cell equals its upper-left neighbour, every diagonal is constant, and a single mismatch proves one is not.

Cells in row 0 or column 0 start their diagonals and have nothing to compare with, so the scan starts at r = 1, c = 1.

Approach: Upper-left neighbour check

  1. Loop r from 1 to m - 1 and c from 1 to n - 1.
  2. If matrix[r][c] != matrix[r - 1][c - 1], return false immediately.
  3. If the loops finish, return true.

Step-by-step example

matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
  1. Row 1: matrix[1][1] = 1 equals matrix[0][0] = 1; matrix[1][2] = 2 equals matrix[0][1] = 2; matrix[1][3] = 3 equals matrix[0][2] = 3.
  2. Row 2: matrix[2][1] = 5 equals matrix[1][0] = 5; matrix[2][2] = 1 equals matrix[1][1] = 1; matrix[2][3] = 2 equals matrix[1][2] = 2.
  3. No mismatch was found, so all six diagonals are constant and the answer is true.

Code: Python, Java, C++

1class Solution:
2    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
3        for r in range(1, len(matrix)):
4            for c in range(1, len(matrix[0])):
5                if matrix[r][c] != matrix[r - 1][c - 1]:
6                    return False
7        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each cell outside row 0 and column 0 is compared once.

Space

O(1)

Only the two loop indices are stored.

Other approaches

Group by diagonal key (time O(m * n), space O(m + n))

Store the first value seen for each c - r in a hash map and compare later cells against it. Same time, but it uses O(m + n) extra space.

Compare shifted rows (time O(m * n), space O(n))

Row r without its first element must equal row r - 1 without its last element. This is the form used when rows arrive one at a time, because only the previous row is needed in memory.

Common mistakes

  • Starting the loops at 0 and reading matrix[-1], which in Python silently wraps to the last row.
  • Comparing with the upper-right neighbour (r - 1, c + 1), which checks anti-diagonals instead.
  • Assuming the matrix is square. Diagonals near the corners of a rectangular matrix are shorter, and the neighbour test handles them without special cases.

Frequently asked questions

Why is checking only the upper-left neighbour enough?

Each diagonal is a chain where every cell's predecessor is its upper-left neighbour. If every link in the chain joins equal values, the whole chain holds one value.

What if the matrix is too large to load into memory at once?

Keep only the previous row. When a new row arrives, check that its elements from index 1 on equal the previous row's elements up to index n - 2, then discard the older row.

What is the time and space complexity of Toeplitz Matrix?

O(m * n) time, since each cell is compared at most once, and O(1) extra space.