0% completed
Solution: Toeplitz Matrix
On This Page
Problem Statement
Solution
Step-by-step Algorithm
Code
Complexity Analysis
Problem Statement
Given an m x n matrix, determine if the given matrix is a Toeplitz matrix.
A Toeplitz matrix is one in which every diagonal from top-left to bottom-right has the same elements.
In other words, the matrix should have the property that each element is equal to the element diagonally down to its right.
Example 1:
- Input:
[[1,2,3],
[4,1,2],
[5,4,1]]
- Expected Output: true
- Justification: All diagonals have the same elements. Diagonals of the above matrix are [5], [4, 4], [1, 1, 1], [2, 2], and [3].
Example 2:
- Input:
[[1,2],
[3,4]]
- Expected Output: false
- Justification: The diagonal are [3], [1, 4], and [2]. A diagonal [1, 2] doesn't have the same elements.
Example 3:
- Input:
[[7,7,7],
[7,7,7],
[7,7,7]]
- Expected Output: true
- Justification: Each diagonal, although containing the same repeated element (7), satisfies the condition of a Toeplitz matrix.
Solution
To solve this problem, we will iterate through the elements of the matrix, checking if each element (except those in the last row and last column) matches with its diagonal successor. This approach works because a Toeplitz matrix is defined by the consistency of elements along its diagonals. By verifying this condition, we can ensure whether the matrix adheres to the Toeplitz criteria.
Step-by-step Algorithm
- Iterate over each row of the matrix, except the last row.
- For each row, iterate over each column, except the last column.
- Check if the current element is equal to the element diagonally down to its right.
- If any such pair of elements is not equal, return false immediately.
- For each row, iterate over each column, except the last column.
- If the entire matrix is iterated without finding any mismatch, return true.
matrix = [[1,2,3],[4,1,2],[5,4,1]]. Check that every cell equals its diagonal successor (one row down, one column right).
1 of 6
Code
Complexity Analysis
- Time Complexity: O(m*n), where
mis the number of rows andnis the number of columns in the matrix. Each element is checked once. - Space Complexity: O(1), as no extra space is used besides a few variables for iteration.
Reading Progress
0%
On This Page
Problem Statement
Solution
Step-by-step Algorithm
Code
Complexity Analysis