Toeplitz matrix

A Toeplitz (or diagonal-constant) matrix is a matrix in which each descending diagonal from left to right is constant, i.e., all elements in a diagonal are the same. Given a rectangular matrix mat, your task is to complete the function isToeplitz which returns 1 if the matrix is Toeplitz otherwise, it returns 0.

Examples:

Input:
mat = [[6, 7, 8],
[4, 6, 7],
[1, 4, 6]]
Output: 1
Explanation: The test case represents a 3x3 matrix 6 7 8 4 6 7 1 4 6 Output: 1(True) as values in all downward diagonals from left to right contain the same elements.
Input: 
mat = [[1,2,3],
[4,5,6]]
Output: 0
Explanation: Matrix of order 2x3 will be 1 2 3 4 5 6 Output: 0(False) as values in all diagonals are not the same.

Constraints:
1<=mat.size,mat[0].size<=40
1<=mat[i][j]<=100

Expected time complexity: O(n*m)
Expected space complexity: O(1)


Approach 01:

#include <vector>

using namespace std;

bool isToepliz(vector<vector<int>>& matrix) {
    int num_rows = matrix.size();
    int num_cols = matrix[0].size();
    
    for (int row = 0; row < num_rows; row++) {
        for (int col = 0; col < num_cols; col++) {
            if (row == col) {
                if (matrix[row][col] != matrix[0][0]) {
                    return false;
                }
            }
        }
    }
    return true;
}
from typing import List

def isToepliz(matrix: List[List[int]]) -> bool:
    num_rows = len(matrix)
    num_cols = len(matrix[0])
    
    for row in range(num_rows):
        for col in range(num_cols):
            if row == col:
                if matrix[row][col] != matrix[0][0]:
                    return False
    return True

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top