We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Transpose File

Number: 194

Difficulty: Medium

Paid? No

Companies: Meta


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.


Code Solutions

# Open the file and read the lines from file.txt
with open('file.txt', 'r') as file:
    # Split each line by space to create a matrix of tokens
    data = [line.strip().split() for line in file.readlines()]

# Transpose the matrix using zip and convert tuples to lists
transposed = list(zip(*data))

# Print each row of the transposed matrix by joining tokens with a space
for row in transposed:
    print(" ".join(row))
← Back to All Questions