I have a LeetCode problem:
Given an M x N matrix, return True if and only if the matrix is Toeplitz.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
My solution is (Swift):
func isToeplitzMatrix(_ matrix: [[Int]]) -> Bool {
if matrix.count == 1 { return true }
for i in 0 ..< matrix.count - 1 {
if matrix[i].dropLast() != matrix[i + 1].dropFirst() { return false }
}
return true
}
As I understood Big O notation, my algorithm's time complexity is O(n), while LeetCode top answers' is O(n^2).
Top answers example:
func isToeplitzMatrix(_ matrix: [[Int]]) -> Bool {
for i in 0..<matrix.count-1 {
for j in 0..<matrix[0].count-1 {
if (matrix[i][j] != matrix[i+1][j+1]) {
return false;
}
}
}
return true;
}
Still, my algorithm takes 36ms (according to LeetCode), while top answer takes 28ms.
When I commented out if matrix.count == 1 { return true }
it took even more time to run - 56ms.