← Home

766. Toeplitz Matrix

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
766

The trick here is to name the state correctly, then let the implementation follow. For 766. Toeplitz Matrix, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are isDiagAllSame, isToeplitzMatrix.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(M*N).
  • Space: O(M+N).

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
03
04Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
05 
06
07Example 1:
08
09Input:
10matrix = [
11  [1,2,3,4],
12  [5,1,2,3],
13  [9,5,1,2]
14]
15Output: True
16Explanation:
17In the above grid, the diagonals are:
18"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
19In each diagonal all elements are the same, so the answer is True.
20Example 2:
21
22Input:
23matrix = [
24  [1,2],
25  [2,2]
26]
27Output: False
28Explanation:
29The diagonal "[1, 2]" has different elements.
30**/
31
32//Runtime: 16 ms, faster than 98.28% of C++ online submissions for Toeplitz Matrix.
33//Memory Usage: 12.4 MB, less than 64.08% of C++ online submissions for Toeplitz Matrix.
34/**
35Complexity Analysis
36
37Time Complexity: O(M*N). 
38(Recall in the problem statement that M, N are the number of rows and columns in matrix.)
39
40Space Complexity: O(M+N).
41**/
42class Solution {
43public:
44    bool isDiagAllSame(vector<vector<int>>& matrix, int i, int j){
45        //i, j: a point to identity a diagonal
46        int base = matrix[i][j];
47        bool allSame = true;
48        
49        i++;
50        j++;
51        
52        while(i<matrix.size() && j<matrix[0].size()){
53            if(matrix[i][j]!=base){
54                allSame = false;
55            }
56            i++;
57            j++;
58        }
59        return allSame;
60    }
61    
62    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
63        /*
64        for M x N matrix
65        (M-1, 0) -> (M-2, 0) -> ... -> (0, 0)
66        -> (0, 1) -> (0, 2) -> (0, 3) -> (0, N-1)
67        */
68        for(int i = matrix.size()-1; i>=0; i--){
69            if(!isDiagAllSame(matrix, i, 0)){
70                return false;
71            }
72        }
73        for(int j = 1; j<matrix[0].size(); j++){
74            if(!isDiagAllSame(matrix, 0, j)){
75                return false;
76            }
77        }
78        return true;
79    }
80};

Cost

Complexity

Time
O(M*N).
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(M+N).
Auxiliary state plus the answer structure where the problem requires one.