Problem
Given a text file file.txt
, transpose its content.
You may assume that each row has the same number of columns, and each field is separated by the ' '
character.
Examples
Example:
If file.txt
has the following content:
|
|
Output the following:
|
|
Solution
Method 1 – Using awk
(Recommended)
Intuition
awk
can process each field and store them by column, then print each column as a row.
Approach
Read each line, store each field in an array by column, then print the columns as rows at the end.
Code
|
|
Complexity
- ⏰ Time:
O(n*m)
where n is the number of rows and m is the number of columns. - 🧺 Space:
O(n*m)
Method 2 – Using Bash Arrays
Intuition
Read all lines, split into words, and reconstruct by columns.
Approach
Read the file into an array, then for each column, print the corresponding field from each row.
Code
|
|
Complexity
- ⏰ Time:
O(n*m)
- 🧺 Space:
O(n*m)