Toeplitz Matrix

Not the cleanest solution but so far this is the only solution I can think of for this easy LC problem.

class Solution {
    fun isToeplitzMatrix(matrix: Array<IntArray>): Boolean {
        var column = matrix.size - 1
        var row = 0
        
        while(column >= 0 && row < matrix[0].size){
            var state = true
            var num = -1
            var x = row
            var y = column            
            while(x < matrix[0].size && y < matrix.size){
                val current = matrix[y++][x++]
                if(num != -1) {
                    state = state and (num == current)
                    if(!state) return false            
                }
                num = current
            }
            
            when {
                column == 0 -> row++
                else -> column--
            }
        }
        
        return true
    }   
}
Runtime: 196 ms, faster than 60.00% of Kotlin online submissions for Toeplitz Matrix.
Memory Usage: 37.2 MB, less than 100.00% of Kotlin online submissions for Toeplitz Matrix.

This seems to be like a brute-force approach and I guess there’s another solution that can navigate through the diagonals in a more efficient way.

comments powered by Disqus