Skip to content

766. Toeplitz Matrix 👍

Approach 1: Regular

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    for (int i = 0; i + 1 < matrix.size(); ++i)
      for (int j = 0; j + 1 < matrix[0].size(); ++j)
        if (matrix[i][j] != matrix[i + 1][j + 1])
          return false;
    return true;
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public boolean isToeplitzMatrix(int[][] matrix) {
    for (int i = 0; i + 1 < matrix.length; ++i)
      for (int j = 0; j + 1 < matrix[0].length; ++j)
        if (matrix[i][j] != matrix[i + 1][j + 1])
          return false;
    return true;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
    for i in range(len(matrix) - 1):
      for j in range(len(matrix[0]) - 1):
        if matrix[i][j] != matrix[i + 1][j + 1]:
          return False

    return True

Approach 2: Follow up 1

  • Time: $O(mn)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    if (matrix.empty())
      return true;

    const int m = matrix.size();
    const int n = matrix[0].size();
    vector<int> buffer(n);

    // load row[0] to buffer
    for (int j = 0; j < n; ++j)
      buffer[j] = matrix[0][j];

    // do rolling array
    for (int i = 1; i < m; ++i) {
      for (int j = 0; j + 1 < n; ++j)
        if (buffer[j] != matrix[i][j + 1])
          return false;
      buffer = matrix[i];
    }

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public boolean isToeplitzMatrix(int[][] matrix) {
    if (matrix.length == 0)
      return true;

    final int m = matrix.length;
    final int n = matrix[0].length;
    int[] buffer = new int[n];

    // load row[0] to buffer
    for (int j = 0; j < n; ++j)
      buffer[j] = matrix[0][j];

    // do rolling array
    for (int i = 1; i < m; ++i) {
      for (int j = 0; j + 1 < n; ++j)
        if (buffer[j] != matrix[i][j + 1])
          return false;
      buffer = matrix[i];
    }

    return true;
  }
}
Back to top