Toeplitz Matrix - Problem
Imagine you're looking at a Toeplitz Matrix - a special type of matrix where every diagonal from top-left to bottom-right contains identical elements! This creates a beautiful pattern where elements "cascade" down and to the right.
Given an m x n matrix, your task is to determine if it follows this special property. Return true if the matrix is Toeplitz, otherwise return false.
What makes a matrix Toeplitz?
- Every diagonal from top-left to bottom-right has the same elements
- For any element at position
(i, j), it should equal the element at(i+1, j+1) - This pattern continues throughout the entire matrix
Example: In matrix [[1,2,3,4],[5,1,2,3],[9,5,1,2]], the diagonals are [1,1,1], [2,2,2], [3,3], [4], [5,5], [9] - all elements in each diagonal are identical!
Input & Output
example_1.py — Valid Toeplitz Matrix
$
Input:
matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
›
Output:
true
💡 Note:
In this matrix, every diagonal has identical elements: [1,1,1], [2,2,2], [3,3], [4], [5,5], [9]. Since all diagonals contain the same elements throughout, it's a valid Toeplitz matrix.
example_2.py — Invalid Toeplitz Matrix
$
Input:
matrix = [[1,2],[2,2]]
›
Output:
false
💡 Note:
The diagonal starting from matrix[0][0] contains [1,2]. Since 1 ≠ 2, this diagonal doesn't have identical elements, making it not a Toeplitz matrix.
example_3.py — Single Element Matrix
$
Input:
matrix = [[5]]
›
Output:
true
💡 Note:
A single element matrix is always considered a Toeplitz matrix since there's only one diagonal with one element, which trivially satisfies the condition.
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Pattern
Visualize the matrix as a staircase with colored diagonals
2
Check Adjacent Steps
Compare each tile with the tile diagonally down-right
3
Verify Consistency
Ensure all diagonal paths maintain the same color
Key Takeaway
🎯 Key Insight: A matrix is Toeplitz if every diagonal from top-left to bottom-right contains identical elements. The optimal solution simply compares each element with its diagonal neighbor (i+1, j+1).
Time & Space Complexity
Time Complexity
O(m × n)
We visit each element once, except the last row and column
✓ Linear Growth
Space Complexity
O(1)
We only use a constant amount of extra space
✓ Linear Space
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 20
- 0 ≤ matrix[i][j] ≤ 99
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code