HomeLeetcode192. Word Frequency - Leetcode Solutions

192. Word Frequency – Leetcode Solutions

Description

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.
  • Each word must consist of lowercase characters only.
  • Words are separated by one or more whitespace characters.

Examples:

Example:

Assume that words.txt has the following content:

the day is sunny the the
the sunny is is
Your script should output the following, sorted by descending frequency:

the 4
is 3
sunny 2
day 1

Solution in Bash

Bash
tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -nr | awk '{print $2, $1}'

Explanation

  • tr -s ' ' '\n' < words.txt: Translates spaces into newlines, converting the text into a list of words, one per line. The -s option ensures that multiple spaces are squeezed into a single space before translation.
  • sort: Sorts the list of words alphabetically.
  • uniq -c: Counts the occurrences of each word.
  • sort -nr: Sorts the counted words in numerical order, in reverse (i.e., highest to lowest).
  • awk '{print $2, $1}': Prints the word (second field) followed by its count (first field).
Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular