Problem 358342 · easy · Phase 03 Linear Management & Searching

Constant Diagonals (Toeplitz Check)

matrix · iteration · diagonals

A grid is Toeplitz if every diagonal running from top-left to bottom-right contains the same value along its whole length. Given an m x n grid matrix, return True if it is Toeplitz and False otherwise.

Examples

Input:  matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
Explanation: the diagonals are [9], [5, 5], [1, 1, 1], [2, 2, 2], [3, 3], [4].

Input:  matrix = [[1, 2], [2, 2]]
Output: False
Explanation: the diagonal [1, 2] is not constant.

Constraints

  • 1 <= m, n <= 500
  • Target: O(m * n) time, O(1) extra space.

Goals

  • Compare each cell with its upper-left neighbour
  • Skip the first row and column, which have no such neighbour
  • Stop early on the first mismatch
Starting Python…