Start learning free

LESSON 47 OF 314 · MATRIX

Transpose Matrix in Kotlin: O(m * n) with Nested Loops

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 6
    Ctrl + Enter to check

    KOTLIN · MATRIX

    Transpose Matrix in Kotlin, explained

    Problem overview

    The method transpose receives matrix, an Array<IntArray> with m rows and n columns, and returns a new Array<IntArray> with n rows and m columns. The value in row i, column j of the input lands in row j, column i of the output.

    For [[6, 0, -3], [2, 9, 4]] (2 rows of 3) the answer has 3 rows of 2. The top row becomes the left column and the bottom row becomes the right column:

    6 2
    0 9
    -3 4
    

    A single column turns into a single row: [[7], [-1], [5], [10]] gives [[7, -1, 5, 10]]. The tests print each row as values separated by spaces.

    Approach

    There is no clever trick here. Every value has exactly one destination, and the rule for finding it is the swap of its two indexes. So the plan is to create the result grid with the swapped shape, visit every cell of the input once, and copy it to result[j][i]. That touches m * n cells, which is the O(m * n) the statement asks for, and it cannot be beaten, because every value has to be read.

    The new grid is needed because the shape changes. A 2 by 3 grid cannot be turned into a 3 by 2 grid inside the same arrays. (Only square grids can be transposed in place, by swapping pairs across the diagonal, but this lesson returns a new grid.)

    Step by step

    1. Measure the input. m is matrix.size, the number of rows. n is matrix[0].size, the number of columns. Every row has the same length, so the first row is enough, and the constraints guarantee at least one row.
    2. Build the result. Array(n) { IntArray(m) } creates n rows, and the block runs once per row to make an IntArray of m zeros. Because the block runs for each row, the rows are separate arrays, not one array shared n times.
    3. Loop over the result's rows. The outer loop variable j goes over 0 until n. Row j of the result will hold column j of the input.
    4. Walk down that column. The inner loop variable i goes over 0 until m, from the top row to the bottom row of the input.
    5. Copy with the indexes traded. result[j][i] = matrix[i][j].
    6. Return result.

    The solution in Kotlin

    class Solution {
        fun transpose(matrix: Array<IntArray>): Array<IntArray> {
            val m = matrix.size
            val n = matrix[0].size
            val result = Array(n) { IntArray(m) }
            for (j in 0 until n) {
                for (i in 0 until m) {
                    result[j][i] = matrix[i][j]
                }
            }
            return result
        }
    }
    

    Kotlin details worth knowing:

    • Array<IntArray> is an array of primitive int arrays. It is the usual choice for a grid of integers, and matrix[i][j] reads and writes it directly.
    • 0 until n stops before n. Writing 0..n would include n and fail with an out-of-bounds exception on the last pass.
    • A new IntArray(m) is filled with zeros, but every cell gets overwritten here, so the zeros never show.

    Complexity

    Time: the two loops run n * m times and each pass does a constant amount of work: O(m * n). Space: the result holds m * n values, so the extra space is also O(m * n). That space is the answer itself, which the method has to return.

    Edge cases and common mistakes

    • Making the result m by n. For a grid that isn't square, Array(m) { IntArray(n) } is the wrong shape, and result[j][i] then fails with an ArrayIndexOutOfBoundsException. The result has n rows of m values.
    • Forgetting to swap the indexes. result[i][j] = matrix[i][j] just copies the grid.
    • One row or one column. Both work with no special case. A 4 by 1 input gives a 1 by 4 result,.
    • Square grids. [[4, -7], [2, 0]] gives [[4, 2], [-7, 0]]. The cells on the main diagonal stay where they are, and the others trade places across it.

    Testing

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