DevPath

← All problems

Transpose Matrix

Easy matrix

Description

Return the transpose of the matrix (rows become columns).

Constraints

1 <= rows, cols <= 100

Examples

Input: matrix = [[1,2,3],[4,5,6]]

Output: [[1,4],[2,5],[3,6]]

Hints (1)
  • The element at (r, c) moves to (c, r).

Solutions

Swap indices. · Time O(rows*cols) · Space O(rows*cols)

func transpose(matrix [][]int) [][]int {
    rows, cols := len(matrix), len(matrix[0])
    out := make([][]int, cols)
    for c := 0; c < cols; c++ {
        out[c] = make([]int, rows)
        for r := 0; r < rows; r++ {
            out[c][r] = matrix[r][c]
        }
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account