Advertisement

Toeplitz Matrix - LeetCode 766 Solution

Toeplitz Matrix - Complete Solution Guide

Toeplitz Matrix is LeetCode problem 766, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

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: Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] Output: true Explanation: In the above grid, the diagonals are: "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". In each diagonal all elements are the same, so the answer is True. Example 2: Input: matrix = [[1,2],[2,2]] Output: false Explanation: T

Detailed Explanation

The problem asks us to determine if a given m x n matrix is a Toeplitz matrix. A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. In other words, for any cell matrix[i][j], it should be equal to matrix[i+1][j+1] as long as both indices are within the bounds of the matrix. We need to return `true` if the matrix is Toeplitz, and `false` otherwise.

Solution Approach

The solution iterates through the matrix, comparing each element with its bottom-right neighbor. If any two such neighbors are not equal, the matrix is not Toeplitz, and we return `false`. If the entire matrix is traversed without finding any unequal neighbors, it means all diagonals have the same elements, and we return `true`.

Step-by-Step Algorithm

  1. Step 1: Iterate through the rows of the matrix from index 0 to rows - 2 (exclusive of the last row).
  2. Step 2: Iterate through the columns of the matrix from index 0 to cols - 2 (exclusive of the last column).
  3. Step 3: Inside the inner loop, compare the current element matrix[i][j] with its bottom-right neighbor matrix[i+1][j+1].
  4. Step 4: If the elements are not equal, immediately return `false` because the matrix is not Toeplitz.
  5. Step 5: After the loops complete without finding any unequal neighbors, return `true` because the matrix is Toeplitz.

Key Insights

  • Insight 1: The core concept is checking if matrix[i][j] == matrix[i+1][j+1] for every valid i and j.
  • Insight 2: We can iterate through the matrix and compare adjacent diagonal elements efficiently.
  • Insight 3: No additional data structures are necessary; we can perform the check in-place.

Complexity Analysis

Time Complexity: O(m*n)

Space Complexity: O(1)

Topics

This problem involves: Array, Matrix.

Companies

Asked at: tcs.