#766

Toeplitz Matrix

Easy
ArrayMatrixArrayMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the observation that if each element in the matrix is equal to its top-left neighbor, then the matrix is Toeplitz. This reduces unnecessary checks and improves efficiency.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through the matrix starting from the second row and second column.
  2. 2Step 2: For each element, check if it is equal to the element diagonally above-left.
  3. 3Step 3: If any element is not equal, return false. If all checks pass, return true.
solution.py9 lines
1# Full working Python code
2
3def isToeplitzMatrix(matrix):
4    rows, cols = len(matrix), len(matrix[0])
5    for i in range(1, rows):
6        for j in range(1, cols):
7            if matrix[i][j] != matrix[i-1][j-1]:
8                return False
9    return True

Complexity note: The time complexity is O(n) because we only check each element once (excluding the first row and column). The space complexity is O(1) since we do not use any additional space.

  • 1Each diagonal in a Toeplitz matrix has the same elements.
  • 2We can check the condition by comparing each element with its top-left neighbor.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.