Problem 766

Abstract / Summary

Check if every diagonal from top left to bottom right has the same number in the matrix.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0766.py

class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        for y in range(1, len(matrix)):
            for x in range(1, len(matrix[0])):
                if matrix[y][x] != matrix[y-1][x-1]:
                    return False
        return True
7 lines | 281 bytes | submitted October 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether a two-dimensional integer array satisfies the Toeplitz property - every diagonal from top-left to bottom-right contains identical values. The method iterates through the matrix, comparing each element (except those in the first row and first column) with the element that lies one row above and one column to the left. If any mismatch is found the function returns False immediately; otherwise it returns True after all relevant cells have been examined.

Core Logic

The algorithm is built around a double loop that starts at the second row and second column. For each position (y, x) it checks the equality with the diagonal predecessor (y-1, x-1). The early return on a mismatch prevents unnecessary work once the Toeplitz condition is violated.

for y in range(1, len(matrix)):
    for x in range(1, len(matrix[0])):
        if matrix[y][x] != matrix[y-1][x-1]:
            return False

If the loops complete without triggering the return, the matrix has passed all diagonal checks and the method concludes with a positive result.

return True

Edge Cases Handled

When the matrix consists of a single row, the outer loop (range(1, len(matrix))) produces no iterations, so the function skips the inner comparison entirely and returns True. The same behavior occurs for a single column because the inner loop (range(1, len(matrix[0]))) yields no iterations. Consequently, matrices of size 1×n or m×1 are correctly identified as Toeplitz without additional conditional logic.

An empty matrix is not explicitly addressed; the code assumes at least one row and one column, which aligns with the typical contract of the problem statement. Within the assumed non-empty context, the implementation safely accesses matrix[0] to obtain the column count.

Performance Characteristics

The solution processes each element exactly once, except for the first row and first column which are excluded by design. By returning immediately upon detecting a violation, the algorithm avoids scanning the remainder of the matrix in non-Toeplitz cases, which can lead to substantial savings for large inputs with early mismatches.

Memory usage is minimal because the algorithm relies solely on index variables and does not allocate auxiliary data structures. All operations are performed in place on the input matrix, preserving the original data without duplication. This in-place approach contributes to a low memory footprint and makes the method suitable for environments with constrained resources.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big grid of colored blocks, kind of like a giant flat puzzle. This code is checking to see if the grid has a special pattern where every diagonal line of blocks has the exact same color. To do this, the code starts at the second row and the second column and looks at each block one by one. It compares the current block to the neighbor sitting diagonally above it to the left. If it finds any block that is a different color than its diagonal neighbor, it knows the pattern is broken and stops. If it makes it all the way through every block without finding any mismatched colors, it discovers that the pattern is perfect.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.19 | σ = 1.12

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java JS Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
39 links | 24 authors | 10 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy
2 solutions   October 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality