Program to Find Transpose of a Matrix

Last Updated : 14 Jul, 2026

Given a matrix mat[][] of size n × n, compute its transpose. The transpose of a matrix is obtained by converting its rows into columns and its 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.

Try It Yourself
redirect icon

[Naive Approach] - Brute Force Matrix Transposition O(n^2) Time and O(n^2) 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.

Step by Step Implementations:

  • Initialize a new matrix of size n × 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.
C++
#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> transpose(vector<vector<int>>& mat) {

    int n = mat.size();

    // Create a result matrix of size n x n
    vector<vector<int>> tMat(n, vector<int>(n));

    // Fill the transposed matrix
    // by swapping rows with columns
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {

            // Assign transposed value
            tMat[j][i] = mat[i][j];
        }
    }

    return tMat;
}

int main() {
    vector<vector<int>> mat = {
        {1, 1, 1, 1},
        {2, 2, 2, 2},
        {3, 3, 3, 3},
        {4, 4, 4, 4}
    };

    vector<vector<int>> res = transpose(mat);

    for (auto& row : res) {
        for (auto& elem : row) {
            cout << elem << " ";
        }
        cout << "\n";
    }

    return 0;
}
Java
import java.util.ArrayList;

public class GFG {

    public static ArrayList<ArrayList<Integer>> transpose(int[][] mat) {

        int n = mat.length;

        // Create a result matrix of size n x n
        ArrayList<ArrayList<Integer>> tMat = new ArrayList<>();

        // Fill the transposed matrix by
        // swapping rows with columns
        for (int i = 0; i < n; i++) {
            ArrayList<Integer> row = new ArrayList<>();
            for (int j = 0; j < n; j++) {
                // Assign transposed value
                row.add(mat[j][i]);
            }
            tMat.add(row);
        }

        return tMat;
    }

    public static void main(String[] args) {

        int[][] mat = {
            {1, 1, 1, 1},
            {2, 2, 2, 2},
            {3, 3, 3, 3},
            {4, 4, 4, 4}
        };

        ArrayList<ArrayList<Integer>> res = transpose(mat);

        for (ArrayList<Integer> row : res) {
            for (int elem : row) {
                System.out.print(elem + " ");
            }
            System.out.println();
        }
    }
}
Python
def transpose(mat):
    n = len(mat)

    # Create a result matrix of size n x n
    tMat = [[0 for _ in range(n)] for _ in range(n)]

    # Fill the transposed matrix by
    # swapping rows with columns
    for i in range(n):
        for j in range(n):

            # Assign transposed value
            tMat[j][i] = mat[i][j]

    return tMat


if __name__ == "__main__":
    mat = [
        [1, 1, 1, 1],
        [2, 2, 2, 2],
        [3, 3, 3, 3],
        [4, 4, 4, 4]
    ]

    res = transpose(mat)

    for row in res:
        for elem in row:
            print(elem, end=" ")
        print()
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static List<List<int>> transpose(int[,] mat) {
        int n = mat.GetLength(0);

        // Create a result matrix of size n x n
        List<List<int>> tMat = new List<List<int>>();

        // Fill the transposed matrix by
        // swapping rows with columns
        for (int j = 0; j < n; j++) {
            List<int> row = new List<int>();
            for (int i = 0; i < n; i++) {

                // Assign transposed value
                row.Add(mat[i, j]);
            }
            tMat.Add(row);
        }

        return tMat;
    }

    public static void Main()
    {
        int[,] mat = {
            {1, 1, 1, 1},
            {2, 2, 2, 2},
            {3, 3, 3, 3},
            {4, 4, 4, 4}
        };

        List<List<int>> res = transpose(mat);
        int n = res.Count;

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                Console.Write(res[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
function transpose(mat) {
    const n = mat.length;

    // Create a result matrix of size n x n
    const tMat = new Array(n).fill(0).map(
        () => new Array(n).fill(0)
    );

    // Fill the transposed matrix by
    // swapping rows with columns
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {

            // Assign transposed value
            tMat[j][i] = mat[i][j];
        }
    }

    return tMat;
}

// Driver code
const mat = [
    [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4]
];

const res = transpose(mat);

for (const row of res) {
    console.log(row.join(" "));
}

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

[Expected Approach] - Using constant space for Square Matrix O(n^2) 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 an in-place algorithm because 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.

C++
#include <iostream>
#include <vector> 
using namespace std;

vector<vector<int>> transpose(vector<vector<int>>& mat) {
    int n = mat.size();  

    // Traverse the upper triangle of the matrix
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            
            // Swap elements across the diagonal
            swap(mat[i][j], mat[j][i]);
        }
    }

    return mat;  
}

int main() {
    
    vector<vector<int>> mat = {
            {1, 1, 1, 1},
            {2, 2, 2, 2},
            {3, 3, 3 ,3},
            {4, 4, 4, 4}
    };

    vector<vector<int>> res = transpose(mat);

    for (const auto& row : res) {
        for (int elem : row) {
            cout << elem << " ";  
        }
        cout << endl; 
    }

    return 0;
}
Java
import java.util.ArrayList;

public class GFG {

    public static ArrayList<ArrayList<Integer>> transpose(int[][] mat) {

        int n = mat.length;

        // Create a result matrix of size n x n
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();

        // Build the transposed matrix
        for (int j = 0; j < n; j++) {
            ArrayList<Integer> row = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                row.add(mat[i][j]);
            }
            result.add(row);
        }

        return result;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {1, 1, 1, 1},
            {2, 2, 2, 2},
            {3, 3, 3, 3},
            {4, 4, 4, 4}
        };

        ArrayList<ArrayList<Integer>> res = transpose(mat);

        int n = res.size();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(res.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}
Python
def transpose(mat):
    
    # Number of rows (and columns, since it's square)
    n = len(mat)  

    # Traverse the upper triangle of the matrix 
    for i in range(n):
        for j in range(i + 1, n):
            
            # Swap elements across the diagonal
            mat[i][j], mat[j][i] = mat[j][i], mat[i][j]

    return mat  


if __name__ == "__main__":
    mat = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
    res = transpose(mat)  
    for row in res:
        print(" ".join(map(str, row)))
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static List<List<int>> transpose(int[,] mat) {

        int n = mat.GetLength(0);

        List<List<int>> result = new List<List<int>>();

        // Build the transposed matrix
        for (int j = 0; j < n; j++) {
            List<int> row = new List<int>();
            for (int i = 0; i < n; i++) {
                row.Add(mat[i, j]);
            }
            result.Add(row);
        }

        return result;
    }

    public static void Main() {
        int[,] mat = {
            {1, 1, 1, 1},
            {2, 2, 2, 2},
            {3, 3, 3, 3},
            {4, 4, 4, 4}
        };

        List<List<int>> res = transpose(mat);

        int n = res.Count;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Console.Write(res[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}
JavaScript
function transpose(mat) {  
    
    // Number of rows (and columns, since it's square)
    const n = mat.length;

    // Traverse the upper triangle of the matrix
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            
            // Swap elements across the diagonal
            let temp = mat[i][j];
            mat[i][j] = mat[j][i];
            mat[j][i] = temp;
        }
    }

    return mat;  
}

// Driver code
const mat = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]];
const res = transpose(mat);  
for (const row of res) {
    console.log(row.join(" "));
}

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