Check diagonal equality in a matrix
Company: Meta
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates skill in matrix manipulation and algorithmic reasoning, specifically understanding diagonal traversal, equality checks, and handling boundary conditions such as empty matrices, single-row or single-column inputs, and negative values.
Constraints
- 0 <= m, n
- matrix is rectangular: every row has the same number of columns
- -10^9 <= matrix[i][j] <= 10^9 (values may be negative)
- An empty matrix (m == 0 or n == 0) returns true
Examples
Input: ([[1,2,3,4],[5,1,2,3],[9,5,1,2]],)
Expected Output: True
Explanation: Every diagonal ([9],[5,5],[1,1,1],[2,2,2],[3,3],[4]) holds equal values, so it is a Toeplitz matrix.
Input: ([[1,2],[2,2]],)
Expected Output: False
Explanation: The main diagonal is [1,2]; matrix[1][1]=2 differs from matrix[0][0]=1, so it is not diagonal-equal.
Hints
- Two cells belong to the same diagonal exactly when their (row - column) value is equal.
- You do not need to walk full diagonals: cell (i, j) is on the same diagonal as cell (i-1, j-1), so just compare each cell to its top-left neighbor.
- Handle empty matrices, single rows, and single columns up front — they are trivially diagonal-equal because no diagonal has length greater than 1.