Algorithms · Visualized
Matrix: Toeplitz
Matrix & 2D
Rotations, traversals, and grid searches on 2D arrays.
A Toeplitz matrix has the same value along every diagonal that runs from top-left to bottom-right. Time: O(m×n) average, O(m×n) — every cell except the first row and column is compared once worst; space: O(1) — no extra matrix is needed.
Big-O: Classic O(m·n) sweeps and in-place tricks.
Toeplitz Matrix
Matrix / 2D ArrayA Toeplitz matrix has the same value along every diagonal that runs from top-left to bottom-right. Equivalently, every cell equals the cell immediately above-left of it, so a[i][j] must equal a[i-1][j-1] wherever both indices exist. That local check is enough to prove the whole matrix is Toeplitz without collecting each diagonal separately.
How Toeplitz Works
- Handle empty input: a matrix with no rows (or no columns) is Toeplitz by definition.
- Start at row 1, column 1 and compare a[i][j] with its upper-left neighbour a[i-1][j-1].
- If any pair differs, return false immediately — the diagonal containing that cell is not constant.
- If the loop finishes, every diagonal is constant, so return true.
Toeplitz Worked Example
Input: [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Compare (1,1)=1 with (0,0)=1 ✓, (1,2)=2 with (0,1)=2 ✓, (1,3)=3 with (0,2)=3 ✓, (2,1)=5 with (1,0)=5 ✓, (2,2)=1 with (1,1)=1 ✓, (2,3)=2 with (1,2)=2 ✓. No mismatch, so the matrix is Toeplitz.
def toeplitz(m):
for r in range(1, len(m)):
for c in range(1, len(m[0])):
if m[r][c] != m[r - 1][c - 1]:
return False
return TrueBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Toeplitz Time & Space Complexity
When to Use Toeplitz
- Validating convolution and signal-processing kernels, where constant diagonals are a structural requirement.
- Detecting repeated structure in spreadsheet-like grids, such as shifted copies of the same row.
- A compact interview exercise in index arithmetic and early-exit scanning.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.