Word Frequency — LeetCode 192 Python Solution

MediumShell
Problem
#192
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

the day is sunny the the
the sunny is is

Python solution

Python
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

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Related problems

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.

Get Stealth Interview