Problem Description
Given a text file file.txt where each row has the same number of columns and fields are separated by a space, transpose its content so that rows become columns. For example, if file.txt contains: name age alice 21 ryan 30 the output would be: name alice ryan age 21 30
Key Insights
- Read and parse each line into a list of tokens using space as the delimiter.
- Store the tokens in a 2D list (or array) representing the matrix.
- Transposing the matrix converts rows into columns.
- Use efficient built-in functions (like zip in Python) or nested loops to perform the transpose.
- Output the result by joining each transposed row with a space.
Space and Time Complexity
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns. Space Complexity: O(m * n), as storage is required for the entire matrix.
Solution
We start by reading the file line by line and splitting each line into its constituent tokens, accumulating these into a matrix structure (a list of lists, for example). Since we assume each row has the same length, we can safely transpose the matrix. In many languages, functions like zip can help with this, or we can use nested loops: the outer loop iterating over the columns and the inner loop over the rows. Finally, each column (the result of the transposition) is output as a space-separated string.