1. Diagonal by Diagonal Traversal from Borders
Intuition
Iterate through every diagonal individually by starting at each border cell in the first row and first column.
Algorithm
- 1. For col from 0 to n-1: trace diagonal from (0, col). If any cell != matrix[0][col], return false.
- 2. For row from 1 to m-1: trace diagonal from (row, 0). If any cell != matrix[row][0], return false.
- 3. Return true.
Diagonal-by-Diagonal Border Traversal
2 of 2 questions left todayPhase 1 — Trace Main Diagonal from (0,0): Start at apex (0,0) val=1
Phase 1 — Trace Main Diagonal from (0,0): Start at apex (0,0) val=1. Follow diagonal down-right: (1,1) val=1, (2,2) val=1. All equal.
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: bool isToeplitzMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); for (int c = 0; c < n; ++c) { int val = matrix[0][c], r = 0, col = c; while (r < m && col < n) { if (matrix[r++][col++] != val) return false; } } for (int r = 1; r < m; ++r) { int val = matrix[r][0], row = r, col = 0; while (row < m && col < n) { if (matrix[row++][col++] != val) return false; } } return true; }}; int main() { Solution sol; vector<vector<int>> matrix = {{1, 2, 3, 4}, {5, 1, 2, 3}, {9, 5, 1, 2}}; bool ans = sol.isToeplitzMatrix(matrix); cout << "Is Toeplitz Matrix: " << (ans ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(M * N)— Visits each matrix cell exactly once along diagonals in O(M * N) time. - Space complexity:
O(1)— Auxiliary space is O(1).
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.