This post is completed by 1 user

  • 0
Add to List
Beginner

479. Most frequent word

Objective: Given an array of string, write a program to find the word in the array which appears the maximum number of times.

Example:

Input: [Algorithms, String, Integer, Integer, Algorithms, String, Integer, Algorithms, String, Algorithms]
Most frequent word: Algorithms

Naive Approach: Use the nested loops, compare the word from the outer loop with all the other elements using the inner loop, and count its appearances. Keep track of the word which appears the maximum number of times.

Time Complexity: O(N2)

Better Approach: Use Map.

Iterate the array and construct a hashmap with the word as the key and its appearances count as value.

Iterate the hashmap and pick the word with the maximum count.

Time Complexity: O(N), Space Complexity: O(N)

Output:

Input: [Algorithms, String, Integer, Integer, Algorithms, String, Integer, Algorithms, String, Algorithms]
Most frequent word: Algorithms