Matrix in Python

Problem 1: Check for a Toeplitz Matrix Problem: You are given an n x n square matrix. Write a function is_toeplitz(matrix) that checks whether the matrix is a Toeplitz matrix. A Toeplitz matrix is one where every descending diagonal from top-left to bottom-right (↘️) contains the same elements. Example: Consider this matrix: 6 7 8 4 6 7 1 4 6 The diagonals are: [1], [4, 4], [6, 6, 6], [7, 7], [8] All elements in each diagonal are equal — so this is a Toeplitz matrix ✅. Breakdown: To check if a matrix is Toeplitz: Loop through each element in the matrix (excluding the last row and column). For each element, compare it with the one diagonally down-right from it. If any of those pairs don’t match, return False. If the loop completes without mismatches, return True. Python Solution: from typing import List def is_toeplitz(matrix: List[List[int]]) -> bool: n = len(matrix) for i in range(n): for j in range(n): if i + 1

May 7, 2025 - 18:55
 0
Matrix in Python

Problem 1: Check for a Toeplitz Matrix

Problem:

You are given an n x n square matrix. Write a function is_toeplitz(matrix) that checks whether the matrix is a Toeplitz matrix.

A Toeplitz matrix is one where every descending diagonal from top-left to bottom-right (↘️) contains the same elements.

Example:

Consider this matrix:

6 7 8
4 6 7
1 4 6

The diagonals are:

  • [1],
  • [4, 4],
  • [6, 6, 6],
  • [7, 7],
  • [8]

All elements in each diagonal are equal — so this is a Toeplitz matrix ✅.

Breakdown:

To check if a matrix is Toeplitz:

  • Loop through each element in the matrix (excluding the last row and column).
  • For each element, compare it with the one diagonally down-right from it.
  • If any of those pairs don’t match, return False.
  • If the loop completes without mismatches, return True.

Python Solution:

from typing import List

def is_toeplitz(matrix: List[List[int]]) -> bool:
    n = len(matrix)

    for i in range(n):
        for j in range(n):
            if i + 1 < n and j + 1 < n:
                if matrix[i][j] != matrix[i + 1][j + 1]:
                    return False

    return True

Test It:

matrix = [
    [6, 7, 8],
    [4, 6, 7],
    [1, 4, 6]
]

print(is_toeplitz(matrix))  # Output: True