Word Frequency - Problem

Write a bash script to calculate the frequency of each word in a text file words.txt.

For simplicity, you may assume:

  • words.txt contains only lowercase characters and space ' ' characters
  • Each word must consist of lowercase characters only
  • Words are separated by one or more whitespace characters

The output should be sorted by frequency in descending order, with the most frequent words first. If two words have the same frequency, sort them alphabetically.

Input & Output

Example 1 — Basic Word Frequency
$ Input: content = "the quick brown fox jumps over the lazy dog"
Output: the 2\nbrown 1\ndog 1\nfox 1\njumps 1\nlazy 1\nover 1\nquick 1
💡 Note: The word 'the' appears 2 times (most frequent), all other words appear once each. Words with same frequency are sorted alphabetically.
Example 2 — Single Word
$ Input: content = "hello"
Output: hello 1
💡 Note: Only one word 'hello' appears once.
Example 3 — Multiple Spaces
$ Input: content = "a b a b a"
Output: a 3\nb 2
💡 Note: Word 'a' appears 3 times, 'b' appears 2 times. Multiple spaces are handled correctly.

Constraints

  • 1 ≤ content.length ≤ 104
  • content contains only lowercase English letters and spaces
  • Words are separated by one or more spaces

Visualization

Tap to expand
Word Frequency Counter: Input → Process → OutputINPUT"the quick brown foxjumps over the lazy dog"PROCESS1. Split into words2. Count frequenciesOUTPUTthe 2, brown 1, dog 1,fox 1, jumps 1, ...Algorithm StepsStep 1: Split text → ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]Step 2: Count frequencies → {"the": 2, "quick": 1, "brown": 1, "fox": 1, ...}Step 3: Sort by frequency desc, then alphabetically → [("the", 2), ("brown", 1), ...]🎯 Key Insight: Hash map for O(n) counting + sorting for proper order
Understanding the Visualization
1
Input
Text string with words separated by spaces
2
Process
Split words, count frequencies, sort results
3
Output
Word-count pairs sorted by frequency desc, alphabetically
Key Takeaway
🎯 Key Insight: Use hash map to count frequencies efficiently, then sort by count descending and alphabetically for consistent results
Asked in
Google 35 Amazon 28 Microsoft 22
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen