Start learning free

LESSON 48 OF 314 · MATRIX

Toeplitz Matrix in JavaScript: Compare with the Up-Left Cell

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

    JAVASCRIPT · MATRIX

    Toeplitz Matrix in JavaScript, explained

    Problem overview

    The method isToeplitzMatrix receives matrix, an array of rows of integers, and returns true if every diagonal holds a single value. A diagonal starts in the top row or the left column and moves one row down and one column right at each step. The method returns false as soon as one diagonal has two different values.

    In the first example, the grid has 4 rows and 3 columns:

    7 3 8
    4 7 3
    6 4 7
    1 6 4
    

    The diagonals hold 1, then 6, 6, then 4, 4, 4, then 7, 7, 7, then 3, 3 and 8. Each repeats a single value, so the answer is true. In [[5, 2, 9, 1], [0, 5, 2, 9], [3, 0, 5, 8]] the diagonal that starts at the 2 in row 0 reads 2, 2, 8, so the answer is false. The statement asks for O(m * n) time and O(1) extra space.

    Approach: check each cell against its predecessor

    A direct plan would walk every diagonal, remember its first value and compare the rest of the cells with it. That needs a loop over the starting cells and another loop along each diagonal, with bounds to get right.

    There is a simpler way to see it. A diagonal holds one value exactly when every cell equals the cell before it on the same diagonal, the one up and to the left, at matrix[i - 1][j - 1]. If each link in the chain matches, the whole chain is equal. So the method looks at every cell that has an up-left neighbor and compares the two.

    The cells with no up-left neighbor are the ones in row 0 and column 0. They only start diagonals, so there is nothing to compare them with. The loops therefore start at 1 for both the row and the column, which also keeps the code from reading outside the grid. Nothing is stored besides a few counters, which gives O(1) extra space.

    Step by step

    1. Measure the grid. Store the row count, matrix.length, in m and the column count, matrix[0].length, in n. Both are const.
    2. Loop over the rows from 1 with i. Row 0 has no row above it.
    3. Loop over the columns from 1 with j, inside the first loop. Column 0 has no column to its left. The two loops reach every other cell once.
    4. Compare the cell with the one up and to the left. If matrix[i][j] differs from matrix[i - 1][j - 1], return false right away. One mismatch is enough to answer.
    5. Return true after the loops. No cell differed from its predecessor, so every diagonal holds a single value.

    The solution in JavaScript

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

    Details worth knowing

    The comparison uses !==, strict inequality. For numbers it behaves like the loose version, but it never converts types, which is a good default.

    A grid with one row or one column never enters the inner loop, or never enters the outer one, so the method returns true without comparing anything. That is correct: every diagonal of such a grid is a single cell.

    JavaScript doesn't stop you from reading outside an array. An index like -1 is just a missing property, so the read gives undefined instead of an error:

    const row = [4, 7, 3];
    console.log(row[-1]);
    
    undefined
    

    That makes off-by-one mistakes in a loop start easy to miss, because the code keeps running and just compares against undefined.

    Complexity

    Time is O(m * n): each of the (m - 1) * (n - 1) inner cells is compared once. Extra space is O(1), since the method adds no arrays. It reads the grid and never changes it.

    Edge cases and common mistakes

    • Comparing with the wrong neighbor. Checking matrix[i][j] against matrix[i - 1][j] (the cell directly above) tests whether columns are constant, not diagonals. On the first example that check gives false, although the correct answer is true.
    • Starting the column loop at 0. Then j - 1 is -1 and the method compares a cell with undefined. On the first example, a loop that starts j at 0 and compares with matrix[i - 1][j - 1] returns false for a grid that should give true.
    • Forgetting the short grids. A single column such as [[3], [8], [3]] is valid and gives true. A single row such as [[1, 2, 3]] also gives true.
    • Checking only the main diagonal. Diagonals that start in the top row and in the left column all count.

    Testing

    • [[7, 3, 8], [4, 7, 3], [6, 4, 7], [1, 6, 4]] gives true.
    • [[5, 2, 9, 1], [0, 5, 2, 9], [3, 0, 5, 8]] gives false.
    • [[3], [8], [3]] gives true.
    • [[1, 2, 3]] gives true.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free