Problem Description
Given an m x n matrix, determine if the matrix is Toeplitz – that is, every diagonal from top-left to bottom-right has all the same elements. Return true if it is a Toeplitz matrix; otherwise, return false.
Key Insights
- Each element (except those in the first row and first column) must be equal to its top-left neighbor.
- You can validate the matrix by iterating from the second row/column and comparing each element with matrix[i-1][j-1].
- This simple check allows you to determine if every diagonal has the same elements without extra space.
- For streaming data (loading one row at a time), maintain the previous row for comparison.
Space and Time Complexity
Time Complexity: O(m * n)
Space Complexity: O(1)
Solution
The problem is solved by iterating through the matrix starting from the element at position (1, 1). For every element at matrix[i][j], compare it with the element at matrix[i-1][j-1]. If any two elements in this pair do not match, the matrix is not Toeplitz. This check ensures that every diagonal from the top-left to bottom-right has identical elements. In terms of auxiliary space, only constant extra space is used, which makes this approach efficient both in time and space.