Skip to content

Added leetcode solution of 0192 #875

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions dsa-solutions/lc-solutions/0100-0199/0192-word-frequency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
id: word-frequency
title: Word Frequency
sidebar_label: 0192 Word Frequency
tags:
- Leetcode
- Bash

description: "This is a solution to the Word Frequency problem."
---

## Problem 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 1:**

```
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

```


### Constraints

- The input text file `words.txt` contains only lowercase characters and spaces.
- Words are separated by one or more whitespace characters.

## Solution for Word Frequency Problem

### Intuition And Approach

To solve this problem using Unix tools, we can leverage a series of commands piped together to process the text file. The approach includes:

1. Replacing spaces with newlines to handle word separation.
2. Sorting the words to prepare for counting duplicates.
3. Using `uniq` to count the occurrences of each word.
4. Sorting the counts in descending order.
5. Formatting the output to display word frequency.

#### Code

<Tabs>
<TabItem value="bash" label="bash">
<SolutionAuthor name="@mahek0620"/>
```bash
tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -nr | awk '{print $2, $1}'
```
</TabItem>
</Tabs>



## References

- **LeetCode Problem:** [Word frequency Problem](https://leetcode.com/problems/word-frequency/)
- **Solution Link:** [Word-Frequency Solution on LeetCode](https://leetcode.com/problems/word-frequency/solutions/5273312/word-frequency-solution)
- **Authors GeeksforGeeks Profile:** [Mahek Patel](https://leetcode.com/u/mahekrpatel611/)
Loading