Start learning free

LESSON 48 OF 314 · MATRIX

Toeplitz Matrix in Java: O(m * n) Time, O(1) Space

Practice O(m · n) Read the full explanation

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

    JAVA · MATRIX

    Toeplitz Matrix in Java, explained

    Problem overview

    The method isToeplitzMatrix gets matrix, an int[][], and returns true when every diagonal holds a single value. A diagonal starts in the top row or the left column and goes one row down and one column right at each step.

    The grid with rows [7, 3, 8], [4, 7, 3], [6, 4, 7] and [1, 6, 4] has six diagonals: 1; 6, 6; 4, 4, 4; 7, 7, 7; 3, 3; and 8. Each repeats one value, so the answer is true. In the grid [5, 2, 9, 1], [0, 5, 2, 9], [3, 0, 5, 8], the diagonal that starts at the 2 in row 0 holds 2, 2 and 8, so the answer is false.

    Approach

    One way is to walk each diagonal from its starting cell and compare every value with the first one. That works, but it needs a loop over the starting cells plus a loop along each diagonal, and it is easy to get the bounds wrong.

    There is a simpler view. A diagonal holds a single value exactly when every cell equals the cell diagonally up and to its left. If cell (i, j) matches (i - 1, j - 1) for every cell that has such a neighbor, then going along any diagonal each value equals the one before it, so they are all equal. This is a local check, so no diagonal needs to be tracked, and no extra memory is used.

    The cells in row 0 and column 0 have no up-left neighbor. They only start diagonals, so they are never the cell being checked.

    Step by step

    1. Store the number of rows in m and the number of columns, matrix[0].length, in n.
    2. Loop i from 1 to m - 1. Row 0 is skipped because nothing is above it.
    3. Loop j from 1 to n - 1. Column 0 is skipped for the same reason. Together the two loops reach every cell that has an up-left neighbor, once.
    4. If matrix[i][j] differs from matrix[i - 1][j - 1], return false at once. One mismatch is enough to answer.
    5. If the loops finish without a mismatch, return true.

    The solution in Java

    class Solution {
        public boolean isToeplitzMatrix(int[][] matrix) {
            int m = matrix.length;
            int n = matrix[0].length;
            for (int i = 1; i < m; i++) {
                for (int j = 1; j < n; j++) {
                    if (matrix[i][j] != matrix[i - 1][j - 1]) {
                        return false;
                    }
                }
            }
            return true;
        }
    }

    Comparing two int values with != compares their numbers, which is what you want here. (It would be a trap only with boxed Integer objects, and this lesson uses a plain int[][].) Because the loops start at 1, a grid with one row or one column never enters the inner body, so the method returns true straight away.

    Complexity

    Time is O(m * n), because each cell is compared once at most. Extra space is O(1): only m, n, i and j are stored, and the grid isn't copied.

    Edge cases and common mistakes

    • A single row or a single column. Every diagonal is one cell, so the answer is always true. The grid [3], [8], [3] returns true, and so does [1, 2, 3, 4].
    • Starting the loops at 0. Then matrix[i - 1][j - 1] reads index -1 and Java throws ArrayIndexOutOfBoundsException.
    • Comparing with the wrong neighbor. The up-left cell matrix[i - 1][j - 1] is the one on the same diagonal. Comparing with matrix[i - 1][j] would test columns, not diagonals.
    • Checking only the first diagonal misses mismatches elsewhere, as the second example shows: the 8 is in the last row.

    Testing

    Running the solution on the samples, and on the single-row grid [1, 2, 3, 4], prints:

    true
    false
    true
    true

    The tests print booleans in lowercase, the same way.

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