You are given a 2D grid of integers. Write a function to check if it is a "Toeplitz matrix". A Toeplitz matrix is a matrix where every diagonal from top-left to bottom-right has the same elements. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given a 2D grid of integers. We need to check if it is a Toeplitz matrix.
Toeplitz matrix: every diagonal from top-left to bottom-right has the same element.
This means for any (i, j) and (i+1, j+1) that are within the grid, grid[i][j] must equal grid[i+1][j+1].
We can traverse the grid and check each element with the one on the next diagonal (if exists).
Approach:
We can iterate over each element (except the last row and last column) and check if it equals the element at (i+1, j+1).
If we find any mismatch, return false.
If all checks pass, return true.
However, note that we don't need to check the last row and last column because they don't have a next diagonal element.
Steps:
for i from 0 to rows-2 (because we check i+1)
for j from 0 to cols-2 (because we check j+1)
if grid[i][j] != grid[i+1][j+1] then return false
Return true.
Example:
grid = [[1,2,3,4],
[5,1,2,3],
[9,5,1,2]]
Check:
(0,0):1 -> (1,1):1 -> ok
(0,1):2 -> (1,2):2 -> ok
(0,2):3 -> (1,3):3 -> ok
(1,0):5 -> (2,1):5 -> ok
(1,1):1 -> (2,2):1 -> ok
(1,2):2 -> (2,3):2 -> ok
But we don't check (0,3) because j+1 would be out of bounds, and similarly for last row.
Let's code accordingly.
However, note: the problem says "every diagonal from top-left to bottom-right". This condition is exactly that for any (i,j) and (i+1,j+1) we have same value.
But wait, what about diagonals that start at the first row or first column? Our method checks all pairs (i,j) that have (i+1, j+1). This covers all diagonals because each diagonal is composed of consecutive pairs.
Alternatively, we can think of iterating by starting points of diagonals. But the above simple nested loop is sufficient and efficient.
Time complexity: O(rows * cols) because we visit each element at most once (except the last row and column, but that's still linear in the number of elements).
Let's write the function.
To determine if a 2D grid of integers is a Toeplitz matrix, we need to verify that every diagonal running from top-left to bottom-right has the same elements. This means for any cell at (i, j), its value should equal the value at (i+1, j+1) if those indices are within bounds.
Approach
We can efficiently check this by iterating through each cell (except those in the last row or last column) and comparing it with the cell diagonally below and to the right. If any mismatch is found, the matrix is not Toeplitz. This approach ensures we check all relevant diagonals in a single pass.
Algorithm:
For each cell (i, j) in the grid:
If i is not the last row and j is not the last column, compare grid[i][j] with grid[i+1][j+1].
If they differ, return False.
If all comparisons pass, return True.
Time Complexity: (O(m \times n)), where (m) is the number of rows and (n) is the number of columns. Each cell (except the last row/column) is checked once.
Space Complexity: (O(1)), as we use only a constant amount of extra space.
Solution Code
python
def is_toeplitz_matrix(grid):
"""
Check if a 2D grid is a Toeplitz matrix.
Args:
grid: List[List[int]] - a 2D list of integers.
Returns:
bool: True if the grid is a Toeplitz matrix, False otherwise.
"""
rows = len(grid)
if rows == 0:
return True
cols = len(grid[0])
for i in range(rows - 1):
for j in range(cols - 1):
if grid[i][j] != grid[i + 1][j + 1]:
return False
return True
Explanation
Edge Handling: If the grid is empty, it trivially satisfies the condition. The loops avoid out-of-bounds access by stopping at rows-2 and cols-2.
Diagonal Check: For each cell (i, j), we compare it with (i+1, j+1). This ensures every diagonal (starting from any cell except the last row/column) has consistent values.
Early Termination: The function returns False immediately upon finding any mismatch, optimizing performance.
Result: If all comparisons pass, the function returns True, confirming the matrix is Toeplitz.