Start learning free

LESSON 297 OF 639 · MATRIX

Transpose Matrix in Go

Practice O(m · n)

You get a grid matrix of integers, with m rows and n columns.

Return its transpose, a new grid with n rows and m columns.

Row 0 of matrix becomes column 0 of the transpose. Row 1 becomes column 1, and so on.

So the value in row i, column j moves to row j, column i.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Return the transpose as an array of rows too.

 

Example 1:

Input: matrix = [
  [6, 0, -3],
  [2, 9, 4]
]
Output: [
  [6, 2],
  [0, 9],
  [-3, 4]
]
Explanation: The top row (6, 0, -3) is now the left column.
The bottom row (2, 9, 4) is now the right column.
2 rows of 3 values became 3 rows of 2.

Example 2:

Input: matrix = [
  [7],
  [-1],
  [5],
  [10]
]
Output: [
  [7, -1, 5, 10]
]
Explanation: The only column turns into the only row.

Example 3:

Input: matrix = [
  [4, -7],
  [2, 0]
]
Output: [
  [4, 2],
  [-7, 0]
]
Explanation: 4 is in row 0, column 0, so it stays put.
0 is in row 1, column 1, so it stays put too.
-7 and 2 trade places.

 

Constraints:

  • m and n are each from 1 to 500.
  • Each value is an integer from -109 to 109.
  • Negative values and repeats are allowed.

Note:

Your solution should run in O(m * n) time.

STEP 1 OF 7
    Ctrl + Enter to check

    Transpose Matrix in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free