MediumNo. 0194

Transpose File — LeetCode 194 Python Solution

Topics
Shell
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

Example
name age
alice 21
ryan 30

Python solution

PythonSolution
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

Time
O(n)
Space · auxiliary
O(1) to O(n)

Related problems

Related problems
No.ProblemDifficulty
0193Valid Phone NumbersEasy
0195Tenth LineEasy
0192Word FrequencyMedium
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy

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.

Free to download. Check it runs on your machine, then pick a plan.