Matrix: Given a matrix, find the transpose of the matrix

Problem Statement:

You are given a matrix.

You need to find the transpose of the matrix.

A transpose of a matrix can be found by converting all rows into columns and columns into rows.

Example:

Input: [[1, 2, 3 ,4],
        [1, 2, 3, 4],
        [1, 2, 3, 4],  
        [1, 2, 3, 4]]

Output: mat[][] = [[1, 1, 1, 1],
                   [2, 2, 2, 2],
                   [3, 3, 3, 3],
                   [4, 4, 4, 4]]

Solution Explanation:

The solution is very simple.

Take a result matrix of the same size.

Now swap the rows to columns, example, if the element is at position [i][j], in transpose it will become [j][i].

Return the result.

Time Complexity: O(n*m)
Space Complexity: O(n*m)

Code Solution

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

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

    int r_len = mat.size();        
    int c_len = mat[0].size();    
    
    vector<vector<int>> result(c_len, vector<int>(r_len));

    for (int i = 0; i < r_len; i++) {
        for (int j = 0; j < c_len; j++) {
            
            result[j][i] = mat[i][j];  
        }
    }

    return result;  
}

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

    vector<vector<int>> result = solution(mat);


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

    return 0;
}

Output

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

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *