Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

194. Transpose File - Leetcode Solution

Problem Description

The "Transpose File" problem on LeetCode asks you to transpose the contents of a given text file. In this context, "transposing" means converting rows into columns and columns into rows, similar to transposing a matrix.

The file is provided as input, where each line represents a row and each value in a row is separated by spaces. The goal is to output the transposed version of the file, where each line corresponds to a column in the original file, and each value is separated by a space.

Key Constraints:

  • The number of columns in each row may not be the same.
  • The output should not have trailing spaces at the end of each line.
  • All data is text, not numbers.
  • There is only one valid solution for each input.

For example, if the input file contains:

name age
alice 21
ryan 30
    

The output should be:

name alice ryan
age 21 30
    

Thought Process

To solve this problem, we need to read the file row by row, split each line into its individual values, and then reorganize these values so that columns become rows.

The brute-force approach would be to keep all the rows in memory, then for each column index, collect the corresponding value from each row. However, we need to handle rows with different numbers of columns, so we have to be careful not to access out-of-bounds elements.

To optimize, we can store all the rows as lists, determine the maximum number of columns, and then iterate over each column index, collecting values from rows that have that column.

This approach is similar to transposing a jagged 2D array, where not all rows are the same length.

Solution Approach

Here is a step-by-step breakdown of the algorithm:

  1. Read the File: Read all lines from the file and strip any trailing newline characters.
  2. Split Lines into Words: For each line, split it by spaces to get the individual values. Store each line as a list of strings.
  3. Find Maximum Columns: Determine the maximum number of columns by checking the length of each row.
  4. Transpose: For each column index (from 0 to max columns - 1), create a new row by collecting the value at that index from each row (if it exists).
  5. Format Output: Join the collected values with spaces to form a line, and print or return the transposed lines.

Why this works: By iterating over column indices and collecting available values, we ensure that we handle rows of different lengths and avoid index errors.

Example Walkthrough

Let's walk through the provided example:

name age
alice 21
ryan 30
    
  1. Split into rows:
    • ["name", "age"]
    • ["alice", "21"]
    • ["ryan", "30"]
  2. Maximum columns: 2
  3. Transpose:
    • For column 0: "name", "alice", "ryan" → "name alice ryan"
    • For column 1: "age", "21", "30" → "age 21 30"
  4. Output lines:
    • name alice ryan
    • age 21 30

Each output line corresponds to a column in the original input.

Time and Space Complexity

Brute-force Approach:

  • Time Complexity: O(R * C), where R is the number of rows and C is the maximum number of columns. We scan every element at least once.
  • Space Complexity: O(R * C), since we store all elements in memory for transposition.
Optimized Approach:
  • Our optimized approach is essentially the same as the brute-force in terms of complexity, as we must read and store all data before transposing. However, we avoid unnecessary operations by only iterating over existing elements.

There is no way to do better than O(R * C) since every element must be visited at least once.

Summary

The "Transpose File" problem is a practical exercise in manipulating 2D data structures and handling edge cases like uneven rows. By reading all data into memory, determining the maximum number of columns, and collecting values column-wise, we can efficiently transpose the file. The key insight is to treat each column as a new row in the output, and to carefully handle missing values in shorter rows. This approach is both simple and robust, making it a great example of data transformation in programming.

Code Implementation

# Read from the file 'file.txt' and print its transposed content to stdout.
with open('file.txt') as f:
    rows = [line.strip().split() for line in f]

max_cols = max(len(row) for row in rows)
for col in range(max_cols):
    transposed = []
    for row in rows:
        if col < len(row):
            transposed.append(row[col])
    print(' '.join(transposed))
      
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
    ifstream infile("file.txt");
    string line;
    vector<vector<string>> rows;
    size_t max_cols = 0;

    while (getline(infile, line)) {
        istringstream iss(line);
        vector<string> row;
        string word;
        while (iss >> word) {
            row.push_back(word);
        }
        if (row.size() > max_cols) max_cols = row.size();
        rows.push_back(row);
    }

    for (size_t col = 0; col < max_cols; ++col) {
        bool first = true;
        for (size_t r = 0; r < rows.size(); ++r) {
            if (col < rows[r].size()) {
                if (!first) cout << " ";
                cout << rows[r][col];
                first = false;
            }
        }
        cout << endl;
    }
    return 0;
}
      
import java.io.*;
import java.util.*;

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("file.txt"));
        List<String[]> rows = new ArrayList<>();
        String line;
        int maxCols = 0;
        while ((line = br.readLine()) != null) {
            String[] parts = line.trim().split("\\s+");
            rows.add(parts);
            if (parts.length > maxCols) maxCols = parts.length;
        }
        br.close();

        for (int col = 0; col < maxCols; col++) {
            StringBuilder sb = new StringBuilder();
            for (int r = 0; r < rows.size(); r++) {
                String[] row = rows.get(r);
                if (col < row.length) {
                    if (sb.length() > 0) sb.append(" ");
                    sb.append(row[col]);
                }
            }
            System.out.println(sb.toString());
        }
    }
}
      
const fs = require('fs');

const lines = fs.readFileSync('file.txt', 'utf8').split('\n').filter(Boolean);
const rows = lines.map(line => line.trim().split(/\s+/));
const maxCols = Math.max(...rows.map(row => row.length));

for (let col = 0; col < maxCols; col++) {
    let transposed = [];
    for (let row of rows) {
        if (col < row.length) {
            transposed.push(row[col]);
        }
    }
    console.log(transposed.join(' '));
}