Toeplitz Matrix - Problem

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

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

In other words, a matrix is Toeplitz if matrix[i][j] == matrix[i+1][j+1] for all valid i and j.

Input & Output

Example 1 — Valid Toeplitz Matrix
$ Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: true
💡 Note: Every diagonal from top-left to bottom-right has the same elements: diagonal [1,1,1], diagonal [2,2,2], diagonal [3,3], diagonal [4], diagonal [5,5], diagonal [9]
Example 2 — Invalid Toeplitz Matrix
$ Input: matrix = [[1,2],[2,2]]
Output: false
💡 Note: The diagonal from top-left has elements [1,2] which are not all the same, so it's not a Toeplitz matrix
Example 3 — Single Element Matrix
$ Input: matrix = [[1]]
Output: true
💡 Note: A single element matrix is always Toeplitz since there are no diagonals to violate the property

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 20
  • 0 ≤ matrix[i][j] ≤ 99

Visualization

Tap to expand
Toeplitz Matrix - Single Pass Comparison INPUT 3x4 Matrix 1 2 3 4 5 1 2 3 9 5 1 2 Yellow: Main diagonal (all 1s) Green: Second diagonal (all 2s) matrix = [ [1,2,3,4],[5,1,2,3],[9,5,1,2] ] Property: m[i][j] == m[i+1][j+1] Each diagonal has same elements ALGORITHM STEPS 1 Iterate Matrix Loop i from 0 to m-2 Loop j from 0 to n-2 2 Compare Diagonal Check: m[i][j] vs m[i+1][j+1] Adjacent diagonal elements 3 Mismatch Check If not equal: return false Exit early on failure 4 Return Result All passed: return true Matrix is Toeplitz Comparisons Made: m[0][0]=1 vs m[1][1]=1 [OK] m[0][1]=2 vs m[1][2]=2 [OK] m[0][2]=3 vs m[1][3]=3 [OK] m[1][0]=5 vs m[2][1]=5 [OK] FINAL RESULT 1 2 3 4 5 1 2 3 9 5 1 2 Each color = Same diagonal All elements match! Output: true Verification: All 6 diagonal comparisons passed successfully [OK] Key Insight: A Toeplitz matrix has the property that each diagonal (top-left to bottom-right) contains identical elements. Instead of checking entire diagonals, we only compare adjacent diagonal neighbors: m[i][j] with m[i+1][j+1]. Time Complexity: O(m*n) | Space Complexity: O(1) - Single pass, constant extra space. TutorialsPoint - Toeplitz Matrix | Single Pass Comparison Approach
Asked in
Google 15 Facebook 12
180.0K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen