Practice › Arrays
Transpose of a Matrix
Easy · Arrays · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print the transpose of an R × C matrix — the C × R matrix whose row i is column i of the original.
Input
First line: R C. Next R lines: C integers each.
Output
C lines with R integers each.
Constraints
- 1 ≤ R, C ≤ 100
- −1000 ≤ a[i][j] ≤ 1000
Example 1
Input
2 3 1 2 3 4 5 6
Output
1 4 2 5 3 6
Example 2
Input
1 1 7
Output
7
Hints
- Element (i, j) moves to (j, i).
- Print column 0 as the first line, column 1 as the second, and so on.
Approach
There is no need to build a new matrix: print, for each column j, the values a[0][j], a[1][j], …, a[R−1][j] on one line. Build the output in one buffer instead of printing number by number.
Complexity: O(R · C) time · O(R · C) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int R, C;
cin >> R >> C;
vector<vector<long long>> a(R, vector<long long>(C));
for (auto &row : a)
for (auto &x : row) cin >> x;
for (int j = 0; j < C; j++)
for (int i = 0; i < R; i++) cout << a[i][j] << (i + 1 < R ? ' ' : '\n');
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
R, C = int(data[0]), int(data[1])
a = [data[2 + i * C : 2 + (i + 1) * C] for i in range(R)]
print("\n".join(" ".join(col) for col in zip(*a)))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int R = Integer.parseInt(st.nextToken()), C = Integer.parseInt(st.nextToken());
String[][] a = new String[R][];
for (int i = 0; i < R; i++) a[i] = br.readLine().trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int j = 0; j < C; j++) {
for (int i = 0; i < R; i++) sb.append(a[i][j]).append(i + 1 < R ? ' ' : '\n');
}
System.out.print(sb);
}
}