Start learning free

LESSON 294 OF 635 · MATRIX

Toeplitz Matrix in Java

Practice O(m · n)

You get a grid of integers, matrix, with m rows and n columns.

Return true if each diagonal of the grid holds a single value. Otherwise, return false.

A diagonal starts in the top row or the left column. From there, each step goes one row down and one column right. A grid like that is called a Toeplitz matrix.

The grid is an array of rows. Each row is an array of integers. Rows are counted from 0 at the top, columns from 0 at the left.

 

Example 1:

Input: matrix = [
  [7, 3, 8],
  [4, 7, 3],
  [6, 4, 7],
  [1, 6, 4]
]
Output: true
Explanation: The grid has six diagonals.
From the bottom-left to the top-right, they hold:
1
6, 6
4, 4, 4
7, 7, 7
3, 3
8
Each one repeats a single value.

Example 2:

Input: matrix = [
  [5, 2, 9, 1],
  [0, 5, 2, 9],
  [3, 0, 5, 8]
]
Output: false
Explanation: Start at the 2 in row 0.
Its diagonal holds 2, 2 and 8.
The 8 breaks the pattern.
All the other diagonals are fine.

Example 3:

Input: matrix = [
  [3],
  [8],
  [3]
]
Output: true
Explanation: The grid has one column.
So each diagonal is a single cell.

 

Constraints:

  • 1 to 500 rows.
  • 1 to 500 columns.
  • All rows have the same length.
  • Each value is a whole number from 0 to 99.

Note:

Your solution should run in O(m * n) time and use O(1) extra space.

STEP 1 OF 5
    Ctrl + Enter to check

    Toeplitz Matrix in Java

    Keep going with Java500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free