LeetCode 766: Toeplitz Matrix Solution

Master LeetCode problem 766 (Toeplitz Matrix), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

766. Toeplitz Matrix

Problem Explanation

Explanation:

To solve this problem, we can iterate through the matrix and check if each element is equal to the element on its top-left diagonal. If we find any mismatch, we return false. If we reach the end of the matrix without finding any mismatches, we return true.

  1. We start by checking each element in the first row and first column of the matrix.
  2. Then, we move diagonally to check the elements on the top-left diagonal for each element in the matrix.
  3. If we find any mismatch, we return false.
  4. If we reach the end of the matrix without any mismatches, we return true.

Time complexity: O(m*n) where m is the number of rows and n is the number of columns in the matrix. Space complexity: O(1) as we are using constant extra space.

:

Solution Code

class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (i > 0 && j > 0 && matrix[i][j] != matrix[i - 1][j - 1]) {
                    return false;
                }
            }
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 766 (Toeplitz Matrix)?

This page provides optimized solutions for LeetCode problem 766 (Toeplitz Matrix) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 766 (Toeplitz Matrix)?

The time complexity for LeetCode 766 (Toeplitz Matrix) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 766 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 766 in Java, C++, or Python.

Back to LeetCode Solutions