VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-find-transpose-of-a-matrix/

⇱ Program to find transpose of a matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to find transpose of a matrix

Last Updated : 13 Aug, 2025

Given a 2D matrix mat[][], compute its transpose. The transpose of a matrix is formed by converting all rows of mat[][] into columns and all columns into rows.

Example:

Input: mat[][] = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
Output: [[1, 2, 3 ,4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]]
Explanation: The output is the transpose of the input matrix, where each row becomes a column. This rearranges the data so that vertical patterns in the original matrix become horizontal in the result.

Input: mat[][] = [[1, 2],
[9, -2]]
Output: [[1, 9],
[2, -2]]
Explanation: The output is the transpose of the input matrix, where each row becomes a column. This rearranges the data so that vertical patterns in the original matrix become horizontal in the result.

[Approach 1] Brute Force Matrix Transposition O(n*m) Time and O(n*m) Space

The idea is to create a new matrix where rows become columns by swapping indices — element at position [i][j] in the original becomes [j][i] in the transposed matrix.

Stepby Step Implementations:

  • Initialize a new matrix of size m × n (rows become columns and vice versa).
  • Iterate through each element of the original matrix.
  • Assign each element from row r and column c in the original matrix to row c and column r in the new matrix.
  • Return the new transposed matrix.

Output
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4 

[Approach 2] Using constant space for Square Matrix O(n*n) Time and O(1) Space

This approach works only for square matrices, where the number of rows is equal to the number of columns. It is called anin-place algorithmbecause it performs the transposition without using any extra space.

Step by Step Implementations:

  • Initialize two nested loops:
    • Outer loop: i from 0 to n-1
    • Inner loop: j from i+1 to n-1
      This avoids diagonal and already swapped positions.
  • Swap elements:
    • For each pair (i, j), swap mat[i][j] with mat[j][i]
    • This mirrors the elements across the main diagonal.
  • Continue until all such upper-triangle elements are swapped with their lower-triangle counterparts.

Output
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4 
Comment