Bash 0192.bash
cat words.txt | tr " " "\n" | grep -v "^$" | sort | uniq --count | sort --numeric-sort --reverse | awk '{print $2, $1 }'
Difficulty
and has an acceptance rate of about 30% (200k+ submissions).
Typical patterns to solve this problem:
- Shell
AI Disclaimer
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.
Code Walkthrough
Overview
The script processes a plain-text file named words.txt and produces a frequency list of the distinct words it contains, sorted from the most frequent to the least. It is built as a pipeline of standard Unix utilities, each performing a specific transformation on the data stream. The design leverages the streaming nature of these tools, allowing the file to be read once and processed without intermediate temporary files.
Reading and tokenising the input
cat words.txt
The cat command streams the entire contents of words.txt to standard output. By feeding this output directly into the next stage, the pipeline avoids loading the whole file into memory. The subsequent tr command converts spaces into newlines, turning the text into a one-word-per-line format.
tr " " "\n"
Because tr works on a byte-wise basis, it efficiently handles any amount of whitespace without allocating additional structures. Empty lines that may arise from consecutive spaces are later removed.
Removing empty entries
grep -v "^$"
The grep -v option discards lines that match the empty-string regular expression, effectively filtering out any blank lines produced by the previous transformation. This step ensures that only genuine word tokens continue through the pipeline, preventing spurious counts for empty strings.
Sorting for grouping
sort
sort arranges the words in lexical order. By doing so, identical words become adjacent, which is a prerequisite for the next stage (uniq) to correctly aggregate occurrences. The implementation of sort uses an external merge sort that writes temporary data to disk only when the input exceeds available memory, thereby scaling gracefully with large files.
Counting unique words
uniq --count
uniq scans the sorted stream and collapses consecutive identical lines, prefixing each unique line with the number of times it appeared. The --count flag produces output in the form <count> <word>. Because the input is already sorted, uniq can operate in a single pass with minimal state, keeping only the current word and its tally.
Ordering by frequency
sort --numeric-sort --reverse
A second sort reorders the <count> <word> pairs based on the numeric value of the count, placing the highest frequencies first. The --numeric-sort option tells sort to interpret the leading field as a number rather than as a string, while --reverse flips the order to descending. This stage benefits from the fact that the data size after uniq is typically much smaller than the original file, making the sort operation fast.
Reformatting the output
awk '{print $2, $1 }'
Finally, awk swaps the two fields so that the word appears before its count, matching the conventional “word frequency” presentation. The awk script processes each line individually, emitting the reformatted result to standard output.
Edge-case handling
The pipeline gracefully deals with several edge conditions. Consecutive spaces or tabs generate empty lines after the tr step; the grep -v "^$" filter removes these, preventing them from being counted as words. Lines that consist solely of whitespace are also eliminated. Because sort and uniq operate on a line-by-line basis, words that contain internal spaces are never split incorrectly; only spaces that act as delimiters are transformed into line breaks. The use of awk to reorder fields ensures that even if a word itself contains numbers, the numeric sort performed earlier remains based on the count field, not on the word content.
Performance optimisations
The script exhibits several performance-focused choices. Streaming data through a pipeline avoids the overhead of creating intermediate files, reducing I/O latency. The initial cat feeds directly into tr, which is a lightweight, in-place character translation that does not allocate large buffers. By sorting before invoking uniq, the pipeline leverages the fact that uniq requires only adjacent duplicates, allowing it to run in constant additional memory. The second sort operates on a dramatically reduced dataset (one line per distinct word), minimizing the amount of data that must be compared and possibly written to temporary storage. The final awk stage is a simple field swap, executed line by line with negligible computational cost. Together, these decisions keep the overall runtime proportional to the size of the input file while keeping memory consumption low.
ELI5 - Simplified Explanation
Imagine you have a big messy pile of building blocks that are all mixed up. This code is like a little robot helper that cleans everything up for you. First, the robot takes your whole pile of blocks and spreads them out into one long line so it can see them better. Then, it looks at the spaces between the words and chops the line everywhere it sees a gap, which turns the long line into a neat single stack of words. After that, the robot looks at the stack and kicks out any empty spaces so that only the real words are left. Now the robot wants to be organized, so it sorts all the words in alphabetical order from A to Z, just like you would organize your books. Once they are sorted, it looks for words that are exactly the same and counts how many times each one appears. Then it takes those counts and sorts them again, but this time it puts the words that appear the most right at the very top of the list. Finally, the robot flips the order of the numbers and the words so that the word comes first, and then it shows you the final list so you can see which words were your favorites.
Code Quality
Complexity Analysis
Similar Problems
- problem 347: Top K Frequent Elements
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 203: Remove Linked List Elements
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 607: Sales Person
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 194: Transpose File
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 585: Investments in 2016
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 626: Exchange Seats
- problem 725: Split Linked List in Parts
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
Extra
- 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