Transpose Matrix

Another short solution for this easy LC problem.

class Solution {
    fun transpose(A: Array<IntArray>): Array<IntArray> {
        val rowSize = A.size
        val colSize = A[0].size
        
        var result = Array(colSize, init = { IntArray(rowSize) {0} })
        (0 until colSize).forEach { row ->
                (0 until rowSize).forEach { column ->
                    result[row][column] = A[column][row]
                }
            }
        
        return result
    }
}
Runtime: 204 ms, faster than 89.47% of Kotlin online submissions for Transpose Matrix.
Memory Usage: 38.2 MB, less than 100.00% of Kotlin online submissions for Transpose Matrix.

We’re going to loop through all matrix elements and just simply assign each (row, column) pair to (column, pair) element in a new matrix.

comments powered by Disqus