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
Difficulty
and has an acceptance rate of about 69% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 599: Minimum Index Sum of Two Lists
Extra
- 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