MediumNo. 0192
Word Frequency — LeetCode 192 Python Solution
- Topics
- Shell
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity sake, you may assume: words.txt contains only lowercase characters and space ' ' characters.
Example
the day is sunny the the the sunny is is
Python solution
from collections import Counter
def word_frequency(path: str = "words.txt") -> None:
with open(path, "r", encoding="utf-8") as f:
words = f.read().split()
counts = Counter(words)
for word, cnt in sorted(counts.items(), key=lambda x: (-x[1], x[0])):
print(f"{word} {cnt}")Complexity
- Time
- O(n)
- Space · auxiliary
- O(1) to O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0193 | Valid Phone Numbers | Easy |
| 0194 | Transpose File | Medium |
| 0195 | Tenth Line | Easy |
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
Frequently asked questions
- How hard is LeetCode 192. Word Frequency?
LeetCode 192. Word Frequency is rated Medium on LeetCode.
- What topics does LeetCode 192. Word Frequency cover?
LeetCode 192. Word Frequency is tagged Shell on LeetCode.