Watch 10 video solutions for Transpose File, a medium level problem involving Shell. This walkthrough by Sahil & Sarra has 421,834 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Example:
If file.txt has the following content:
name age alice 21 ryan 30
Output the following:
name alice ryan age 21 30
Problem Overview: The file file.txt contains rows of space-separated words. The task is to transpose the file so that the first column becomes the first row, the second column becomes the second row, and so on. Essentially, treat the input as a matrix of words and output its transpose.
Approach 1: Using Arrays for Transpose (Time: O(m*n), Space: O(m*n))
This approach reads the entire file and stores words using a 2D structure. Split each line into tokens and place them in an array using row and column indices. After loading the data, iterate column by column and print elements across all rows. The key idea is treating the input as a matrix where arr[row][col] holds each word. This method is straightforward and mirrors classic matrix transpose logic often used in arrays problems.
Approach 2: Using Stream Processing (Time: O(m*n), Space: O(n))
Instead of storing the entire matrix, process the file line by line and build column strings dynamically. Tools like awk allow referencing fields ($1, $2, etc.) while reading each line. Maintain an array where index i accumulates the i-th column. Each time a new row is read, append the field to its column string. After processing all lines, print the accumulated column strings. This streaming pattern avoids storing every cell individually and is idiomatic for shell scripting.
Recommended for interviews: The array-based approach demonstrates the core idea clearly: load the grid and print columns as rows. It mirrors standard matrix transpose logic, so it’s easy to reason about. The stream-processing approach is more practical for shell environments and large files because it processes input incrementally. Showing both demonstrates that you understand both algorithmic thinking and real-world shell scripting.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Array-Based Transpose | O(m*n) | O(m*n) | When you want a straightforward matrix-style implementation and memory is not a constraint |
| Stream Processing (awk/field accumulation) | O(m*n) | O(n) | When processing large files or writing idiomatic shell scripts that avoid storing the full matrix |