Problem 194

Abstract / Summary

Read a file and output its rows and columns swapped so each column becomes a row.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Bash 0194.bash

cat file.txt | awk '{ nf=NF; for (i=1; i<=nf; i++) t[i]=t[i]" "$i } END { for (i=1; i<=nf; i++) print(t[i]) }' | sed "s/^ //"
1 lines | 127 bytes | submitted September 6, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 33% (100k+ submissions).

Typical patterns to solve this problem:
  • Shell
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The script processes a text file line-by-line, collects each column across all lines, and finally emits one line per column containing the concatenated values. The pipeline consists of three stages: a cat command that streams the file, an awk program that builds the column strings, and a sed command that removes an unwanted leading space from each output line.

Reading the Input

cat file.txt |

The cat utility opens file.txt and streams its contents to the next stage of the pipeline. By feeding the data through standard output, the script can handle arbitrarily large files without loading the entire file into memory at once. The use of a pipe ensures that each line is processed as soon as it becomes available.

Accumulating Columns with awk

awk '{
    nf = NF
    for (i = 1; i <= nf; i++)
        t[i] = t[i] " " $i
}
END {
    for (i = 1; i <= nf; i++)
        print(t[i])
}'

The awk program performs the core transformation.

  • The variable nf captures the number of fields (NF) on the current line. This value determines how many iterations the inner loop will execute.
  • The for loop iterates over each field index i. For each column, the script appends a space followed by the field value $i to the array element t[i]. Because t[i] is initially empty, the first concatenation yields a leading space that is later removed.
  • The END block runs after all input lines have been read. It iterates from 1 to nf-the field count from the last processed line-and prints each accumulated column string stored in t[i].

Edge Cases Handled by the awk Stage

When a line contains no fields (for example, an empty line), NF is zero, so nf becomes zero and the inner loop does not execute. This means that empty lines do not disturb the existing column accumulations. If the file ends with a line that has fewer fields than earlier lines, the END block will only print up to the number of fields present in that final line, naturally limiting output to columns that have data in the last record.

Because awk treats any sequence of whitespace as a field separator, lines with irregular spacing are normalized: multiple spaces or tabs between words are collapsed, and leading/trailing whitespace does not generate empty fields. This behavior ensures consistent column alignment regardless of the original spacing.

Trimming the Leading Space with sed

sed "s/^ //"

Each column string built by awk begins with a space due to the concatenation pattern " " $i. The sed substitution command removes that initial space from every line of output. The regular expression ^ matches a space at the start of a line, and the replacement is empty, effectively stripping the unwanted character.

Edge Cases Handled by the sed Stage

If a column string happens to be empty-possible when the input file contains no data-the substitution finds no leading space, leaving the line unchanged (which is an empty line). This behavior gracefully handles the case of an entirely empty input without producing spurious characters.

Performance Optimizations Observed

The script processes the file in a single pass through awk, avoiding multiple reads or temporary storage on disk. By accumulating column data in an in-memory array, it eliminates the need for external sorting or intermediate files. The use of a pipeline ensures that each stage begins work as soon as data becomes available from the previous stage, enabling streaming processing and reducing overall latency.

The awk implementation leverages built-in variables (NF, $i) and simple arithmetic, which are highly optimized in the interpreter. The final sed operation is a lightweight substitution that runs in linear time over the output, adding minimal overhead.

Overall, the combination of streaming input, in-memory accumulation, and a minimal post-processing step results in an efficient solution for transposing columnar data from a text file.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big stack of building blocks, and on each block, there is a word written. You have lines of blocks, and you want to turn them sideways so that the first word of every line becomes a new column, the second word of every line becomes the next column, and so on.

First, the computer reads your file one line at a time. It keeps a little notebook where it remembers each word it sees, keeping track of which column that word belongs in. It puts all the first words in a row, all the second words in another row, and continues until it has looked at every single word in your file.

Once it reaches the end of your file, it looks at its notebook and prints out all those new rows it built. Because the computer was very careful to add a tiny space before every word while it was building those rows, there is one pesky little empty space at the very start of every line. The last part of the command is like a tiny robot with an eraser that goes through and cleans up those extra spaces at the beginning, leaving you with perfect columns of your words.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 21 | median = 3 | μ = 4.19 | σ = 1.89

Complexity Analysis

not analyzed yet

Solved On The Same Day

26 easy 21 medium 5 hard
53 solutions   September 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality