Toeplitz Matrix — LeetCode 766 Python Solution

EasyArrayMatrix
Problem
#766
Reading time
2 min

The problem

Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.

Example

Input
matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output
true
Explanation
In the above grid, the diagonals are:

Python solution

Python
class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        m, n = len(matrix), 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

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the number of rows and columns of the matrix, respectively
SpaceO(1) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 766. Toeplitz Matrix is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 766. Toeplitz Matrix?
LeetCode 766. Toeplitz Matrix is rated Easy on LeetCode.
What is the time complexity of LeetCode 766. Toeplitz Matrix?
The Python solution on this page runs in O(m \times n), where m and n are the number of rows and columns of the matrix, respectively.
What is the space complexity of LeetCode 766. Toeplitz Matrix?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 766. Toeplitz Matrix cover?
LeetCode 766. Toeplitz Matrix is tagged Array and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview