229. Constant Diagonals

A weaving machine produces a rectangular pattern, recorded as the grid grid of thread colours. The designers want patterns where every diagonal stripe has one single colour. A diagonal stripe is a line of cells that starts at some cell in the top row or in the left column and keeps going down and to the right, that is [i][j], [i + 1][j + 1], [i + 2][j + 2] and so on until the edge of the grid.

Return true if every diagonal stripe in the grid contains cells that are all equal, and false otherwise. A diagonal made of a single cell is always fine.

Example 1

Input:
grid = [[5,3,8],[2,5,3],[7,2,5]]
Output:
true
Explanation:

The main diagonal is 5,5,5; the diagonal 3,3 and the diagonal 2,2 are constant; the single cells 8 and 7 are trivially fine. The answer is true.

Example 2

Input:
grid = [[1,2],[2,2]]
Output:
false
Explanation:

The main diagonal contains 1 and 2, which are different, so the answer is false.

Example 3

Input:
grid = [[4,1,9,7],[6,4,1,9],[3,6,4,1]]
Output:
true
Explanation:

Every stripe is constant: 4,4,4 then 1,1,1 then 9,9 then 7, and also 6,6 and 3. The answer is true.

Constraints

1 ≤ grid.length, grid[0].length ≤ 50
0 ≤ grid[i][j] ≤ 99

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(m × n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…