Problem 192

Abstract / Summary

Given a text and a list of words count how many times each word appears in the text and return the counts for each word.

Note

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

Bash 0192.bash

cat words.txt | tr " " "\n" | grep -v "^$" | sort | uniq --count | sort --numeric-sort --reverse | awk '{print $2, $1 }'
1 lines | 122 bytes | submitted September 6, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 30% (200k+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 20 | median = 7 | μ = 6.70 | σ = 2.03

Complexity Analysis

not analyzed yet

Similar Problems

1 similar problem

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