MediumNo. 0192

Word Frequency — LeetCode 192 Python Solution

Topics
Shell
Reading time
2 min

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

Example
the day is sunny the the
the sunny is is

Python solution

PythonSolution
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

Related problems
No.ProblemDifficulty
0193Valid Phone NumbersEasy
0194Transpose FileMedium
0195Tenth LineEasy
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.