Similar Problems

Similar Problems not available

Word Frequency - Leetcode Solution

Companies:

LeetCode:  Word Frequency Leetcode Solution

Difficulty: Unknown

Topics: unknown  

The Word Frequency problem on LeetCode is a problem that asks us to find the frequency of each word in a given text document. This problem is a classic example of a word count problem and can be solved using various algorithms and data structures.

Problem Statement:

Write a program to find the frequency of each word in a text document.

Example:

Input: "Hello World, I am a chatbot. I am here to assist you." Output: Hello: 1 World: 1 I: 2 am: 2 a: 1 chatbot: 1 here: 1 to: 1 assist: 1 you: 1

Solution:

To solve the Word Frequency problem, we can follow the below approach:

  1. Split the text document into individual words. We can do this by using any delimiter, such as space, comma, or period.

  2. Create a dictionary to store the frequency of each word. The keys of the dictionary will be the words and the values will be the frequency of each word.

  3. Loop through each word in the text document and increment the counter of the corresponding key in the dictionary.

  4. Finally, print the frequency of each word.

Code:

Here is the Python code to solve the Word Frequency problem:

def word_frequency(text):
    words = text.split()
    frequency = {}
    for word in words:
        if word not in frequency:
            frequency[word] = 1
        else:
            frequency[word] += 1
    return frequency

text = "Hello World, I am a chatbot. I am here to assist you."
frequency = word_frequency(text)
for word, count in frequency.items():
    print(word + ": " + str(count))

Output:

The above code will output the following:

Hello: 1
World,: 1
I: 2
am: 2
a: 1
chatbot.: 1
here: 1
to: 1
assist: 1
you.: 1

In the above output, we can see that the frequency of each word in the given text has been calculated correctly.

Time Complexity:

The time complexity of the above algorithm is O(n), where n is the number of words in the text document. This is because we are looping through each word in the text document only once.

Space Complexity:

The space complexity of the above algorithm is also O(n), where n is the number of words in the text document. This is because we are creating a dictionary to store the frequency of each word. The space required for the dictionary is proportional to the number of unique words in the text document.

Word Frequency Solution Code

1