766. Toeplitz Matrix
Problem description:
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:
1 | Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] |
Example 2:
1 | Input: matrix = [[1,2],[2,2]] |
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
Follow up:
What if the
matrix
is 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
matrix
is so large that you can only load up a partial row into the memory at once?
Solution:
1 | def isToeplitzMatrix(self, m): |
- Follow up 1 :
For the follow-up 1, we are only able to load one row at one time, so we have to use a buffer (1D data structure) to store the row info. When next row comes as a streaming flow, we can compare each value (say, matrix[i][j], i>=1, j>=1) to the “upper-left” value in the buffer (buffer[j - 1]); meanwhile, we update the buffer by inserting the 1st element of the current row (matrix[i][0]) to buffer at position 0 (buffer[0]), and removing the last element in the buffer.
1 | class Solution { |
- Follow up 2: can only load a partial row at one time
two file pointer, the first one start at [0][0], the second one starts at [1][1], load two elements each time, compare and move
Another idea:
We could split the whole matrix vertically into several sub-matrices, while each sub-matrix should have one column overlapped. We repeat the same method in follow-up 1 for each sub-matrix.
For example:
1 | [1 2 3 4 5 6 7] [1 2 3 4] [4 5 6 7] |
time complexity: $O()$
space complexity: $O()$
reference:
related problem: