Toeplitz Matrix - Solution & Explanation
Problem Statement
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.
Example 1:
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] Output: true Explanation: In the above grid, the diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True.
Example 2:
Input: matrix = [[1,2],[2,2]] Output: false Explanation: The diagonal "[1, 2]" has different elements.
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 200 <= matrix[i][j] <= 99
Follow up:
- What if the
matrixis stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once? - What if the
matrixis so large that you can only load up a partial row into the memory at once?
Approach Overview
Problem Overview: A matrix is called a Toeplitz matrix if every diagonal from top-left to bottom-right contains the same element. Given an matrix, verify that each diagonal has identical values. If any diagonal contains different numbers, the matrix is not Toeplitz.
Approach 1: Iterative Check for Diagonal Consistency (Time: O(m*n), Space: O(1))
The simplest observation: every element should match the element diagonally above it. For any cell matrix[i][j], the previous element on the same diagonal is matrix[i-1][j-1]. Iterate through the matrix starting from row 1 and column 1. If you ever find matrix[i][j] != matrix[i-1][j-1], the Toeplitz property is violated.
This works because each diagonal progresses exactly one step down and one step right. Instead of explicitly traversing diagonals, you compare each element with its top-left neighbor during a single pass through the grid. The algorithm uses a straightforward nested loop over the array structure and performs constant-time comparisons.
This approach runs in O(m*n) time since every cell is visited once, and it uses O(1) extra space because no additional data structures are required. For most interview scenarios and production code, this is the cleanest and most efficient solution.
Approach 2: Use HashMap to Track Diagonals (Time: O(m*n), Space: O(m+n))
Each diagonal in a matrix can be uniquely identified by the difference row - col. All elements with the same value of row - col belong to the same diagonal. You can store the first value encountered for each diagonal in a hash map.
Traverse the matrix once. For each cell, compute key = row - col. If the key is not present in the map, store the current value as the expected value for that diagonal. If it already exists, compare the stored value with the current cell. A mismatch means the matrix is not Toeplitz.
This technique explicitly groups elements by diagonals instead of relying on neighbor comparisons. The time complexity remains O(m*n), but the map stores up to m+n-1 diagonals, giving O(m+n) space usage. It is useful when diagonal grouping logic is needed for extensions of the problem.
Recommended for interviews: The iterative comparison approach is what interviewers typically expect. It demonstrates that you recognize the diagonal relationship matrix[i][j] == matrix[i-1][j-1] and can validate the matrix in a single pass with constant space. The hash map method still works and shows understanding of diagonal indexing, but it introduces unnecessary memory overhead for this specific problem.
Approach 1: Approach 1: Iterative Check for Diagonal Consistency
This method involves checking each element of the matrix to ensure that it equals the element diagonally ahead of it - that is, for each cell matrix[i][j], it should be equal to matrix[i+1][j+1], provided both indices are within bounds.
In C, we use nested loops to iterate over each element, excluding the last row and column, to check if matrix[i][j] equals matrix[i+1][j+1]. If any element fails this check, we immediately return false.
Complexity
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns.
Space Complexity: O(1), since no additional data structures are used.
Approach 2: Approach 2: Use HashMap to Track Diagonals
We can use a HashMap (or dictionary) to maintain the first element of each diagonal. Each key represents the difference between row and column indices, and the value is the first element at this diagonal. While iterating, if a new element violates this rule, the matrix isn't Toeplitz.
In this Python implementation, a dictionary keeps track of each diagonal. The key (i - j) refers to a specific diagonal, and its value is the element that should be the same for all elements in this diagonal.
Complexity
Time Complexity: O(m * n)
Space Complexity: O(m + n) for storing diagonal mappings.
Approach 3: Single Traversal
According to the problem description, the characteristic of a Toeplitz matrix is that each element is equal to the element in its upper left corner. Therefore, we only need to iterate through each element in the matrix and check if it is equal to the element in its upper left corner.
The time complexity is O(m times n), where m and n are the number of rows and columns of the matrix, respectively. The space complexity is O(1).
Code
Python
Java
C++
Go
TypeScript
Rust
JavaScript
Complexity Comparison
| Approach | Complexity |
|---|---|
| Approach 1: Iterative Check for Diagonal Consistency | Time Complexity: O(m * n) where |
| Approach 2: Use HashMap to Track Diagonals | Time Complexity: O(m * n) |
| Single Traversal | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Check for Diagonal Consistency | O(m*n) | O(1) | Best general solution. Minimal memory usage and a single pass through the matrix. |
| HashMap to Track Diagonals | O(m*n) | O(m+n) | Useful when explicitly grouping or processing diagonals by index. |
Video Solution
TOEPLITZ MATRIX | LEETCODE # 766 | PYTHON SOLUTION • Cracking FAANG • 8,926 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Toeplitz Matrix easy or hard?
How to solve Toeplitz Matrix in O(n)?
What is the best approach for Toeplitz Matrix?
Is Toeplitz Matrix asked at Google/Amazon/Meta?
What data structure is used in Toeplitz Matrix?
What is the time complexity of Toeplitz Matrix?
Toeplitz Matrix Python or Java solution approach?
Ready to solve this problem?
Practice Toeplitz Matrix with our built-in code editor and test cases.
Practice on FleetCodeTable of Contents
Practice this problem
Open in Editor