Skip to content

Practice Word Frequency

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#192
LeetCode Problem

Word Frequency

Problem Statement

Read words.txt with a Bash script and print each word followed by its frequency, highest frequency first. Words contain lowercase English letters and are separated by whitespace. Every word has a different frequency, so no tie rule is needed. Practice approach: Normalize whitespace into one word per line, discard empty tokens, sort words, count equal adjacent words, then sort numerically by count descending and print word before count. A counting map in awk also works. Test repeated spaces and line breaks; counting lines alone does not count words.

Source: Word Frequency on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
red  blue red
red green blue
Output
red 3
blue 2
green 1
Explanation

red occurs three times, blue twice, and green once across both lines.

Constraints

Words contain lowercase letters.
Words are separated by one or more whitespace characters.
Distinct words have distinct frequencies.

Related LeetCode Problems

Practice more problems similar to Word Frequency.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.