easy

Transpose Matrix

Flip a matrix over its main diagonal.

1. Define the problem

Transpose Matrix

Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the row and column indices of every element. For every cell, the value at matrixi[j] moves to resultj[i] .

Constraints

  • m == matrix.length
  • n == matrixi.length
  • 1 ≤ m, n ≤ 1000
  • -109 ≤ matrixi[j] ≤ 109

Example

Inputmatrix = [[1, 2, 3], [4, 5, 6]]
Output[[1, 4], [2, 5], [3, 6]]

Explanation Row 0 [1, 2, 3] becomes column 0 of the result, and row 1 [4, 5, 6] becomes column 1.

2. Know the words first

In plain terms

Transpose
Flipping a grid of values so that rows become columns and columns become rows.
3. Visualize the solution

Swap row and column indices for every cell

Swap row and column indices for every cell
Statusinit

matrix[0][0]=1 moves to result[0][0]=1.

What happens in this step

matrix[0][0] = 1
result[0][0] = matrix[0][0] = 1
Step 1 of 4

Steps to visualize

  1. Create a new result grid with rows and columns swapped in size.
  2. Walk through every cell (i, j) of the original matrix.
  3. Place matrixi[j] into resultj[i].
  4. Once every cell has been copied, the result is the transposed matrix.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Swap row and column indices for every cell
Statusinit

matrix[0][0]=1 moves to result[0][0]=1.

What happens in this step

matrix[0][0] = 1
result[0][0] = matrix[0][0] = 1
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function transpose(matrix) {
  const m = matrix.length;
  const n = matrix[0].length;
  const result = Array.from({ length: n }, () => new Array(m).fill(0));

  for (let i = 0; i < m; i++) {
    for (let j = 0; j < n; j++) {
      result[j][i] = matrix[i][j];
    }
  }

  return result;
}
Time
O(m * n)
Space
O(m * n)
6. Test cases

Test cases

InputExpectedCovers
matrix = [[1, 2, 3], [4, 5, 6]][[1, 4], [2, 5], [3, 6]]example from the docstring
matrix = [[1, 2], [3, 4]][[1, 3], [2, 4]]a square matrix transposed in place conceptually
matrix = [[5]][[5]]smallest valid input, a 1x1 matrix
matrix = [[1, 2, 3]][[1], [2], [3]]a single row becomes a single column
matrix = [[1], [2], [3]][[1, 2, 3]]a single column becomes a single row
matrix = [[-1, -2], [-3, -4]][[-1, -3], [-2, -4]]negative values transposed correctly