878372. Transpose of Matrix

Easy

Transpose of Matrix

Slug: transpose-of-matrix-1587115621--165510 Difficulty: Easy Id: 878372 Topic Tags: Matrix, Data Structures Company Tags: MakeMyTrip, InfoEdge, Bloomberg

Summary

The problem is about transposing a given matrix. Transposition of a matrix involves flipping the elements in the matrix i.e., changing all row elements into column elements and vice versa. The key concept involved is matrix manipulation.

Detailed Explanation

To solve this problem, we can simply swap the rows with columns. This can be done using two nested loops where the outer loop iterates over each element of the original matrix and the inner loop places it in the transposed matrix.

Here's a step-by-step breakdown:

  1. Create a new matrix to store the transposed elements.
  2. Iterate through each row of the original matrix.
  3. For each row, iterate through each column.
  4. Place the current element from the original matrix into the corresponding position in the transposed matrix.
  5. Continue these steps until all elements have been processed.

Time complexity: O(mn), where m is the number of rows and n is the number of columns in the matrix. Space complexity: O(mn) for storing the transposed matrix.

Optimized Solutions

Java

View on GeeksforGeeks
public int[][] transpose(int[][] matrix) {
    int[][] transposed = new int[matrix[0].length][matrix.length];
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            transposed[j][i] = matrix[i][j];
        }
    }
    return transposed;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.