LeetCode 194: Transpose File Solution

Master LeetCode problem 194 (Transpose File), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

194. Transpose File

Medium

Problem Explanation

Explanation

To transpose a file, we need to read the input file line by line and store each field in a 2D list where the rows represent the original columns and the columns represent the original rows. Then, we can iterate over this 2D list to generate the transposed content.

  • Time complexity: O(N*M) where N is the number of rows and M is the number of columns in the input file.
  • Space complexity: O(N*M) to store the transposed content.

Solution Code

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TransposeFile {
    public static void main(String[] args) {
        List<List<String>> rows = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(" ");
                for (int i = 0; i < fields.length; i++) {
                    if (rows.size() <= i) {
                        rows.add(new ArrayList<>());
                    }
                    rows.get(i).add(fields[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (FileWriter fw = new FileWriter("output.txt")) {
            for (List<String> row : rows) {
                fw.write(String.join(" ", row) + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 194 (Transpose File)?

This page provides optimized solutions for LeetCode problem 194 (Transpose File) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 194 (Transpose File)?

The time complexity for LeetCode 194 (Transpose File) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 194 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 194 in Java, C++, or Python.

Back to LeetCode Solutions