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
- 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, somatrix[0]exists. - 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 holdsnslots, and each slot is anilslice with length 0. - Loop over
jfrom 0 whilej < n. Each pass produces one finished row of the answer. - Give row
jits storage:result[j] = make([]int, m). It starts asmzeros. Without this line the row would still benil, and the assignment in the next step would panic with an index-out-of-range error. - Open the inner loop over
ifrom 0 whilei < m. It goes down columnjof the input, from the top row to the bottom row. - 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. - 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
[][]intis 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 mademake([][]int, 2)prints as[[] []], and its first row isnilwith length 0. - The result is a new grid. Writing to
resultnever touchesmatrix. 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 settingresult[0][1] = 99. - The loop order is a choice. The solution fills the result row by row (
joutside), 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 bothmandnmust be used, and they are:nfor the outer slice and loop,mfor 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
nrows (the input's column count), and each row hasmvalues. Writingmake([][]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. Withoutresult[j] = make([]int, m), rowjhas length 0 and the first write panics.appendwould 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, checklen(matrix) == 0first. - 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]withmatrix[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]].
