Transpose Matrix

Updated on 08 July, 2025
Transpose Matrix header image

Problem Statement

In this problem, given a two-dimensional integer array named matrix, the task is to compute its transpose. The transpose of a matrix involves flipping the matrix over its main diagonal. This operation results in switching the matrix's rows and columns. For example, the element that was at the second row, first column in the original matrix (before transpose) will be found at the first row, second column in the transposed matrix.

Examples

Example 1

Input:

matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output:

[[1,4,7],[2,5,8],[3,6,9]]

Example 2

Input:

matrix = [[1,2,3],[4,5,6]]

Output:

[[1,4],[2,5],[3,6]]

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 1000
  • 1 <= m * n <= 105
  • -109 <= matrix[i][j] <= 109

Approach and Intuition

The process of transposing a matrix is straightforward given the nature of array indexing in programming:

  1. Create a new matrix transpose of dimensions n x m where n is the number of columns in the original matrix, and m is the number of rows. This is the reverse of the original matrix dimensions which is m x n.

  2. Traverse through each element matrix[i][j] in the original matrix:

    • The element at position (i, j) in the original matrix will be placed at position (j, i) in the transposed matrix.
    • Iterate i through rows (0 to m-1) and j through columns (0 to n-1), and for each element at the (i, j) position in the original matrix, assign it to the (j, i) position in the transposed matrix.

Example walkthroughs based on provided examples:

  • Example 1:

    • Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
    • The transposed matrix will have each original element's indices swapped:
      • matrix[0][0] stays matrix[0][0]
      • matrix[0][1] becomes matrix[1][0]
      • ...
      • matrix[2][2] stays matrix[2][2]
    • Output: [[1,4,7],[2,5,8],[3,6,9]] which is the transposed matrix.
  • Example 2:

    • Input: matrix = [[1,2,3],[4,5,6]]
    • Following the same transposing process:
      • matrix[0][1] becomes matrix[1][0]
      • matrix[1][2] becomes matrix[2][1]
    • Output: [[1,4],[2,5],[3,6]], achieved by flipping the rows and columns based on the dimensions of the input matrix ensuring all entries switch according to the index switch.

Through this approach, the operation effectively transforms the matrix by flipping indices over its main diagonal, meeting the requirements stated in the problem.

Solutions

  • Java
java
class Solution {
    public int[][] matrixTranspose(int[][] matrix) {
        int rows = matrix.length, cols = matrix[0].length;
        int[][] transposed = new int[cols][rows];
        for (int i = 0; i < rows; ++i)
            for (int j = 0; j < cols; ++j) {
                transposed[j][i] = matrix[i][j];
            }
        return transposed;
    }
}

To transpose a matrix in Java, follow these steps:

  1. Define a method matrixTranspose that accepts a 2-dimensional integer array matrix.
  2. Define the number of rows (rows) and columns (cols) in the matrix using matrix.length and matrix[0].length, respectively.
  3. Create a new 2-dimensional integer array transposed with its dimensions switched, i.e., cols rows and rows columns.
  4. Use nested loops:
    • Outer loop runs from 0 to rows
    • Inner loop runs from 0 to cols
  5. In the inner loop, assign each element from the original matrix to the transposed matrix using transposed[j][i] = matrix[i][j].
  6. After filling the transposed array, return it from the function.

This method effectively swaps rows with columns, yielding the transpose of the given matrix.

  • Python
python
class Solution:
    def matrix_transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        rows, cols = len(matrix), len(matrix[0])
        transposed = [[None] * rows for _ in range(cols)]
        for row_idx, row in enumerate(matrix):
            for col_idx, element in enumerate(row):
                transposed[col_idx][row_idx] = element
        return transposed

The provided Python solution demonstrates an effective approach for transposing a matrix. Start by initiating the function matrix_transpose, which accepts a two-dimensional list (matrix) as input. Here's how the function works:

  1. Determine the number of rows and columns in the input matrix using len(matrix) and len(matrix[0]).
  2. Create a new matrix called transposed using a list comprehension. This matrix has its dimensions switched (columns become rows and vice versa), initialized with None.
  3. Iterate through each element of the original matrix using nested for loops. Use enumerate to get both the index and the value.
  4. Assign elements from the original matrix to their new positions in the transposed matrix. This is done inversely where the column indices of the original become row indices in the new matrix, and the original row indices become column indices.
  5. After populating the transposed matrix completely, return it.

This script ensures that every element in the matrix is repositioned correctly, thus transforming the matrix from its original to its transposed form efficiently.

Comments

No comments yet.