↓Skip to main content
  1. LeetCode/

LeetCode 766: Toeplitz Matrix

·2 mins· ·
LeetCode Easy Array Matrix
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-06

  • Submissions: Wrong Answer ×2 → Accepted

Approach
#

Cells on the same top-left to bottom-right diagonal share i - j (Matrix Template 3). All diagonals are constant exactly when matrix[i][j] == matrix[i - 1][j - 1] for every i, j >= 1: one pass that only needs the previous row, which also fits the follow-up of reading one row at a time.

My Attempts
#

The first two padded each row with Nones to straighten the diagonals and pulled them out with zip, but the padded rows have different lengths, so zip truncates to the shortest and some diagonals are never compared; the None check was also wrong, sending a column with None and a single value into the elif: [[1], [1]] returned False and [[0, 1], [0, 1], [1, 0]] returned True. Comparing row against row passed.

Solution
#

class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        return all(matrix[i][j] == matrix[i - 1][j - 1]
                   for i in range(1, len(matrix)) for j in range(1, len(matrix[0])))

Complexity
#

Time O(mn), space O(1).

Mistakes to Avoid
#

  • Compare only with the upper-left neighbor; there is no need to extract whole diagonals.

Interview Explanation
#

Constant diagonals mean every cell equals its upper-left neighbor, so one comparison pass suffices, needing only the previous row. Time O(mn), space O(1).

Related

LeetCode 733: Flood Fill
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 733 note: DFS or BFS from the start, recoloring 4-directional cells that share the start’s original color; return immediately if the colors are equal
LeetCode 661: Image Smoother
·2 mins
LeetCode Easy Array Matrix
LeetCode 661 note: each cell becomes the floored average of the existing cells in its 3 × 3 neighborhood, written into a new matrix
LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)
LeetCode 463: Island Perimeter
·2 mins
LeetCode Easy Array Depth-First-Search Breadth-First-Search Matrix
LeetCode 463 note: each land cell contributes 4 edges, minus 2 for each land neighbor above or to the left
LeetCode 744: Find Smallest Letter Greater Than Target
·1 min
LeetCode Easy Array Binary-Search
LeetCode 744 note: find the first letter > target (an upper bound), wrapping around to the first letter if none exists
LeetCode 747: Largest Number At Least Twice of Others
·2 mins
LeetCode Easy Array Sorting
LeetCode 747 note: find the largest and second largest in one pass and return the largest’s index if it is at least twice the second; multiply to avoid dividing by zero