Formatted question description: https://leetcode.ca/all/872.html

766. Toeplitz Matrix (Easy)

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
 

Example 1:

Input:
matrix = [
  [1,2,3,4],
  [5,1,2,3],
  [9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

Input:
matrix = [
  [1,2],
  [2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.


Note:

  1. matrix will be a 2D array of integers.
  2. matrix will have a number of rows and columns in range [1, 20].
  3. matrix[i][j] will be integers in range [0, 99].


Follow up:

  1. What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
  2. What if the matrix is so large that you can only load up a partial row into the memory at once?

Solution 1.

// OJ: https://leetcode.com/problems/toeplitz-matrix
// Time: O(MN)
// Space: O(1)
class Solution {
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        int M = matrix.size(), N = matrix[0].size();
        for (int i = 0; i < M; ++i) {
            for (int x = i + 1, y = 1; x < M && y < N; ++x, ++y) {
                if (matrix[x][y] != matrix[x - 1][y - 1]) return false;
            }
        }
        for (int i = 1; i < N; ++i) {
            for (int x = 1, y = i + 1; x < M && y < N; ++x, ++y) {
                if (matrix[x][y] != matrix[x - 1][y - 1]) return false;
            }
        }
        return true;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/toeplitz-matrix
// Time: O(MN)
// Space: O(1)
class Solution {
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        for (int i = 1; i < matrix.size(); ++i) {
            for (int j = 1; j < matrix[0].size(); ++j) {
                if (matrix[i][j] != matrix[i - 1][j - 1]) return false;
            }
        }
        return true;
    }
};

Java

  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean leafSimilar(TreeNode root1, TreeNode root2) {
            if (root1 == null && root2 == null)
                return true;
            else if (root1 == null || root2 == null)
                return false;
            List<Integer> leafValueSequence1 = leafValueSequence(root1);
            List<Integer> leafValueSequence2 = leafValueSequence(root2);
            if (leafValueSequence1.size() != leafValueSequence2.size())
                return false;
            int size = leafValueSequence1.size();
            for (int i = 0; i < size; i++) {
                if (leafValueSequence1.get(i) != leafValueSequence2.get(i))
                    return false;
            }
            return true;
        }
    
        public List<Integer> leafValueSequence(TreeNode root) {
            List<Integer> leafValueSequence = new ArrayList<Integer>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            boolean flag = true;
            while (!queue.isEmpty()) {
                int size = queue.size();
                if (!flag) {
                    for (int i = 0; i < size; i++) {
                        TreeNode node = queue.poll();
                        leafValueSequence.add(node.val);
                    }
                } else {
                    flag = false;
                    for (int i = 0; i < size; i++) {
                        TreeNode node = queue.poll();
                        TreeNode left = node.left, right = node.right;
                        if (left == null && right == null)
                            queue.offer(node);
                        else {
                            flag = true;
                            if (left != null)
                                queue.offer(left);
                            if (right != null)
                                queue.offer(right);
                        }
                    }
                }
            }
            return leafValueSequence;
        }
    }
    
  • // OJ: https://leetcode.com/problems/toeplitz-matrix
    // Time: O(MN)
    // Space: O(1)
    class Solution {
    public:
        bool isToeplitzMatrix(vector<vector<int>>& matrix) {
            int M = matrix.size(), N = matrix[0].size();
            for (int i = 0; i < M; ++i) {
                for (int x = i + 1, y = 1; x < M && y < N; ++x, ++y) {
                    if (matrix[x][y] != matrix[x - 1][y - 1]) return false;
                }
            }
            for (int i = 1; i < N; ++i) {
                for (int x = 1, y = i + 1; x < M && y < N; ++x, ++y) {
                    if (matrix[x][y] != matrix[x - 1][y - 1]) return false;
                }
            }
            return true;
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def leafSimilar(self, root1, root2):
            """
            :type root1: TreeNode
            :type root2: TreeNode
            :rtype: bool
            """
            leaves1 = []
            leaves2 = []
            self.inOrder(root1, leaves1)
            self.inOrder(root2, leaves2)
            return leaves1 == leaves2
        
        def inOrder(self, root, leaves):
            if not root:
                return
            self.inOrder(root.left, leaves)
            if not root.left and not root.right:
                leaves.append(root.val)
            self.inOrder(root.right, leaves)
    

All Problems

All Solutions