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.txtcontains 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code