Transpose File — LeetCode 194 Python Solution

MediumShell
Problem
#194
Reading time
2 min

The 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.

Example

name age
alice 21
ryan 30

Python solution

Python
def transpose_file(path: str = "file.txt") -> None:
    with open(path, "r", encoding="utf-8") as f:
        rows = [line.strip().split() for line in f]
    if not rows:
        return
    cols = len(rows[0])
    for c in range(cols):
        print(" ".join(row[c] for row in rows))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 194. Transpose File?
LeetCode 194. Transpose File is rated Medium on LeetCode.
What topics does LeetCode 194. Transpose File cover?
LeetCode 194. Transpose File is tagged Shell on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview