Toeplitz Matrix

Easy Arrays & Hashing Matrix Traversal

Toeplitz Matrix is a easy arrays & hashing problem solved with the matrix traversal pattern. The best approach, optimal (compare with the top-left neighbour), runs in O(m · n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from map of diagonals up.

Problem

You are given an m x n integer grid matrix. Return true if the grid is a Toeplitz matrix and false otherwise.

A grid is Toeplitz when every diagonal that runs from top-left to bottom-right holds the same value in all of its cells. In other words, for every cell (r, c) that has a neighbour at (r - 1, c - 1), the two cells hold equal values.

Examples

Example 1

Input
matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output
true
Why
Each diagonal that runs down and to the right holds one value: [9], [5, 5], [1, 1, 1], [2, 2, 2], [3, 3] and [4].

Example 2

Input
matrix = [[1, 2], [2, 2]]
Output
false
Why
The main diagonal holds 1 and then 2, so it is not made of one repeated value.

Example 3

Input
matrix = [[7, 8, 9]]
Output
true
Why
With a single row, every diagonal has just one cell.

Constraints

  • m == matrix.length, n == matrix[i].length
  • 1 <= m, n <= 20
  • 0 <= matrix[i][j] <= 99

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Map of diagonalsO(m · n)O(m + n)
Walk each diagonalO(m · n)O(1)
Optimal (compare with the top-left neighbour)O(m · n)O(1)

1Map of diagonals

TimeO(m · n)Each of the m · n cells is visited once with a constant-time map lookup.
SpaceO(m + n)There are m + n - 1 diagonals, so the map holds at most that many keys.

Every cell on one down-right diagonal has the same value of r - c. Keep a map from that key to the first value seen on the diagonal. Each later cell with the same key must hold that same value.

  1. Make an empty map from diagonal key (r - c) to a value.
  2. Visit every cell (r, c) in row order.
  3. If the key r - c is new, store matrix[r][c] for it.
  4. Otherwise, if the stored value differs from matrix[r][c], return false.
  5. After the loop, return true.
class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
        Map<Integer, Integer> first = new HashMap<>();
        for (int r = 0; r < matrix.length; r++) {
            for (int c = 0; c < matrix[0].length; c++) {
                int key = r - c;
                if (!first.containsKey(key)) {
                    first.put(key, matrix[r][c]);
                } else if (first.get(key) != matrix[r][c]) {
                    return false;
                }
            }
        }
        return true;
    }
}

2Walk each diagonal

TimeO(m · n)Every cell lies on exactly one diagonal, so it is checked once in total.
SpaceO(1)Only a few loop variables.

Each diagonal starts either in the top row or in the left column. From every start, step down and to the right until you leave the grid, checking that each cell matches the start value. No extra storage is needed.

  1. Write a helper same(r, c) that keeps v = matrix[r][c] and moves to (r + 1, c + 1) while inside the grid, returning false on any cell that is not v.
  2. Call it for every start in the top row: (0, c) for each column c.
  3. Call it for every start in the left column below the top: (r, 0) for r from 1.
  4. Return true only if every call returned true.
class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        for (int c = 0; c < n; c++) {
            if (!same(matrix, 0, c)) return false;
        }
        for (int r = 1; r < m; r++) {
            if (!same(matrix, r, 0)) return false;
        }
        return true;
    }

    private boolean same(int[][] matrix, int r, int c) {
        int v = matrix[r][c];
        while (r < matrix.length && c < matrix[0].length) {
            if (matrix[r][c] != v) return false;
            r++;
            c++;
        }
        return true;
    }
}

3Optimal (compare with the top-left neighbour)

TimeO(m · n)One comparison for each cell outside the top row and the left column.
SpaceO(1)No storage beyond the two loop indexes.

A diagonal holds one value exactly when each of its cells equals the cell just before it on that diagonal. So it is enough to check every cell that has a top-left neighbour against that neighbour. This also reads the matrix row by row, which works even if only two rows fit in memory at once.

  1. For r from 1 to m - 1 and c from 1 to n - 1:
  2. If matrix[r][c] != matrix[r - 1][c - 1], return false.
  3. After the loops, return true.
class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
        for (int r = 1; r < matrix.length; r++) {
            for (int c = 1; c < matrix[0].length; c++) {
                if (matrix[r][c] != matrix[r - 1][c - 1]) return false;
            }
        }
        return true;
    }
}

Edge cases to test

  • A single cell (true)
  • A single row or a single column: every diagonal has one cell (true)
  • Only the very last cell breaks the pattern
  • Every value the same (true)
  • A wide or tall matrix, not just a square one

Hints

Hint 1

All cells on one down-right diagonal share the same value of row - column.

Hint 2

You do not need to walk whole diagonals. A matrix is Toeplitz exactly when every cell equals the cell up and to its left.

Hint 3

Start from row 1 and column 1 and compare matrix[r][c] with matrix[r - 1][c - 1]. Stop at the first mismatch.

FAQ

What is the best time complexity for Toeplitz Matrix?

Optimal (compare with the top-left neighbour) runs in O(m · n) time and O(1) extra space. One comparison for each cell outside the top row and the left column.

Which pattern does Toeplitz Matrix use?

It is a arrays & hashing problem that uses the matrix traversal pattern. Other problems with the same pattern: Spiral Matrix, Best Meeting Point, Diagonal Traverse.

Is there a brute force solution for Toeplitz Matrix?

Yes. Map of diagonals takes O(m · n) time and O(m + n) space. Every cell on one down-right diagonal has the same value of r - c.

Which edge cases should I test for Toeplitz Matrix?

A single cell (true); A single row or a single column: every diagonal has one cell (true); Only the very last cell breaks the pattern; Every value the same (true); A wide or tall matrix, not just a square one.