Start learning free

LESSON 47 OF 314 · MATRIX

Transpose Matrix in Go: Nested Loops and make

Practice O(m · n) Read the full explanation

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

    GO · MATRIX

    Transpose Matrix in Go, explained

    Problem overview

    The function transpose receives matrix, a [][]int with m rows and n columns, and returns a new grid with n rows and m columns. The value at row i, column j of the input lands at row j, column i of the output. Row 0 becomes column 0, row 1 becomes column 1, and so on.

    For the grid with rows [6 0 -3] and [2 9 4] (2 rows, 3 columns), the result is [[6 2] [0 9] [-3 4]]: 3 rows of 2 values. A grid that is one column of four values, [[7] [-1] [5] [10]], becomes the single row [[7 -1 5 10]]. A square grid such as [[4 -7] [2 0]] becomes [[4 2] [-7 0]]: the diagonal stays put and the other cells trade places across it.

    The task has to run in O(m * n) time. Each value has to be moved once, so that is as fast as the problem allows.

    Approach: build the answer one row at a time

    The shape changes, so the grid can't be rearranged in place unless it is square. The simplest way is to build a fresh grid of the right size and copy every value across with its two indexes swapped.

    The new grid has n rows because the input has n columns. Each new row j holds the input's column j, which has m values (one per input row). So the outer loop runs over j from 0 to n - 1, creating row j, and the inner loop runs over i from 0 to m - 1, walking down column j of the input and filling the new row.

    Step by step

    1. Read the sizes. m := len(matrix) is the number of rows. n := len(matrix[0]) is the number of columns, which is the length of the first row because all rows have the same length. The constraints guarantee at least one row, so matrix[0] exists.
    2. Create the outer slice with make([][]int, n). In Go, a slice of slices is made in two layers. This call makes only the outer layer: it holds n slots, and each slot is a nil slice with length 0.
    3. Loop over j from 0 while j < n. Each pass produces one finished row of the answer.
    4. Give row j its storage: result[j] = make([]int, m). It starts as m zeros. Without this line the row would still be nil, and the assignment in the next step would panic with an index-out-of-range error.
    5. Open the inner loop over i from 0 while i < m. It goes down column j of the input, from the top row to the bottom row.
    6. Copy one value: result[j][i] = matrix[i][j]. This is the whole idea of a transpose. The two indexes swap places between the right-hand side and the left-hand side.
    7. After both loops, return result.

    The solution in Go

    func transpose(matrix [][]int) [][]int {
        m := len(matrix)
        n := len(matrix[0])
        result := make([][]int, n)
        for j := 0; j < n; j++ {
            result[j] = make([]int, m)
            for i := 0; i < m; i++ {
                result[j][i] = matrix[i][j]
            }
        }
        return result
    }

    Some Go details are worth knowing here.

    • A [][]int is not a rectangle. It is a slice whose elements are themselves slices. That is why the rows are created one at a time inside the loop. A freshly made make([][]int, 2) prints as [[] []], and its first row is nil with length 0.
    • The result is a new grid. Writing to result never touches matrix. After changing a value in the transpose of [[1 2] [3 4]], the input still prints as [[1 2] [3 4]], while the transpose prints as [[1 99] [2 4]] after setting result[0][1] = 99.
    • The loop order is a choice. The solution fills the result row by row (j outside), so writes are sequential and reads jump between input rows. Swapping the loops would make the opposite trade. Either is O(m * n) here.
    • Indexes are plain ints. Go does not allow an unused variable, so both m and n must be used, and they are: n for the outer slice and loop, m for the row length and inner loop.

    Complexity

    Time is O(m * n): the inner statement runs once for each of the m * n values, and the make calls zero m * n slots in total. Space is O(m * n) for the new grid, which is the output itself. Beyond the output, only a few integers are used.

    Edge cases and common mistakes

    • Swapping the sizes. The outer slice has n rows (the input's column count), and each row has m values. Writing make([][]int, m) instead only works for square grids. On the 2 by 3 example, it panics with an index-out-of-range error.
    • Forgetting the inner make. Without result[j] = make([]int, m), row j has length 0 and the first write panics. append would also work, but sizing the row up front is simpler here.
    • Reading matrix[0] blindly. This is safe because the lesson guarantees at least one row. In a function of your own that accepts any slice, check len(matrix) == 0 first.
    • Single rows and single columns. They are not special cases. A 1 by 4 row turns into a 4 by 1 column. For instance, [[1 2 3]] becomes [[1] [2] [3]].
    • Square grids. The trick of swapping matrix[i][j] with matrix[j][i] in place only works for squares, and only if you visit each pair once. For a general grid, build a new one as above.

    Testing

    Try these in the editor above. They all come from running the solution:

    • [[6 0 -3] [2 9 4]] gives [[6 2] [0 9] [-3 4]].
    • [[7] [-1] [5] [10]] gives [[7 -1 5 10]].
    • [[4 -7] [2 0]] gives [[4 2] [-7 0]].
    • [[1 2 3]] gives [[1] [2] [3]].
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free