Most frequent word in an array of strings
Given an array of words arr[], The task is to find the most occurring word in arr[].
Examples:
Input : arr[] = {“geeks”, “for”, “geeks”, “a”,
“portal”, “to”, “learn”, “can”,
“be”, “computer”, “science”,
“zoom”, “yup”, “fire”, “in”,
“be”, “data”, “geeks”}
Output : geeks
Explanation : “geeks” is the most frequent word in the given array occurring 3 timesInput: arr[] = {“hello”, “world”}
Output: world
Most frequent word in an array of strings By Using Nested Loops:
The idea is to run a loop for each word and count the frequency of the word using a nested loop
Follow the below steps to Implement the idea:
- Traverse a loop for each word in the given array
- Run a nested loop and count the frequency of the word
- Initialize res = “” and freq = 0, to store the resulting string and the frequency of the string.
- If the frequency of the word is greater than the freq
- Update freq to the frequency of current word.
- Update res to current word.
- Print res and freq as the final answer.
Below is the Implementation of the above approach.
C++
// CPP code to find most frequent word in// an array of strings#include <bits/stdc++.h>using namespace std;void mostFrequentWord(string arr[], int n){ // freq to store the freq of the most occuring variable int freq = 0; // res to store the most occuring string in the array of // strings string res; // running nested for loops to find the most occuring // word in the array of strings for (int i = 0; i < n; i++) { int count = 0; for (int j = i + 1; j < n; j++) { if (arr[j] == arr[i]) { count++; } } // updating our max freq of occured string in the // array of strings if (count >= freq) { res = arr[i]; freq = count; } } cout << "The word that occurs most is : " << res << endl; cout << "No of times: " << freq << endl;}// Driver codeint main(){ // given set of keys string arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = sizeof(arr) / sizeof(arr[0]); mostFrequentWord(arr, n); return 0;} |
Java
/*package whatever //do not write package name here */import java.io.*;class GFG{ static void mostFrequentWord(String arr[], int n) { // freq to store the freq of the most occuring variable int freq = 0; // res to store the most occuring string in the array of // strings String res = ""; // running nested for loops to find the most occuring // word in the array of strings for (int i = 0; i < n; i++) { int count = 0; for (int j = i + 1; j < n; j++) { if (arr[j].equals(arr[i])) { count++; } } // updating our max freq of occured string in the // array of strings if (count >= freq) { res = arr[i]; freq = count; } } System.out.println("The word that occurs most is : " + res); System.out.println("No of times: " + freq); } public static void main (String[] args) { // given set of keys String arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = arr.length; mostFrequentWord(arr, n); }}// This code is contributed by aadityaburujwale. |
Python3
def mostFrequentWord(arr, n): # freq to store the freq of the most occuring variable freq = 0 # res to store the most occuring string in the array of strings res = "" # running nested for loops to find the most occuring # word in the array of strings for i in range(0, n, 1): count = 0 for j in range(i + 1, n, 1): if arr[j] == arr[i]: count += 1 # updating our max freq of occured string in the # array of strings if count >= freq: res = arr[i] freq = count print("The word that occurs most is : " + str(res)) print("No of times: " + str(freq))# Driver code# given set of keysarr = [ "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks",]n = len(arr)# function callmostFrequentWord(arr, n)# This code is contributed by ajaymakavana. |
C#
using System;class GFG { // Function to find minimum operation // to convert string into palindrome static void mostFrequentWord(string[] arr, int n) { // freq to store the freq of the most occuring // variable int freq = 0; // res to store the most occuring string in the // array of strings string res = ""; // running nested for loops to find the most // occuring word in the array of strings for (int i = 0; i < n; i++) { int count = 0; for (int j = i + 1; j < n; j++) { if (arr[j] == arr[i]) { count++; } } // updating our max freq of occured string in // the array of strings if (count >= freq) { res = arr[i]; freq = count; } } Console.WriteLine("The word that occurs most is : " + res); Console.WriteLine("No of times: " + freq); } // Driver Code public static void Main() { string[] arr = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = 18; // Function Call mostFrequentWord(arr, n); }}// This code is contributed by garg28harsh. |
The word that occurs most is : geeks No of times: 2
Time Complexity: O(N*N), when N is the size of the given array.
Auxiliary Space: O(1)
Most frequent word in an array of strings By Using 2 Hashmaps:
The Idea is to maintain 2 Hashmaps, one to record the first occurence of the word and second to count the frequency of the word.
Follow the below steps to Implement the idea:
- Initialize two Hashmaps freq and occurrence.
- Initialize result = “”, max = 0, and k = 1.
- Travese a loop from 1 till N
- If the current word exist in the occurrence hashmap:
- then continue.
- Else update occurrence[arr[i]] = k
- Increment k by 1
- If the current word exist in the occurrence hashmap:
- Traverse another loop from 1 till N
- Increment the count of the current element in freq by 1
- If max <= freq[arr[i]]
- if max < freq[arr[i]]
- Update max = freq[arr[i]]
- Update result = arr[i]
- Else
- if occurence[result] < occurence[freq[arr[i]]]
- Update max = freq[arr[i]]
- Update result = arr[i]
- if occurence[result] < occurence[freq[arr[i]]]
- if max < freq[arr[i]]
- Return result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std;class Solution {public: // Function to find most frequent word // in an array of strings. string mostFrequentWord(string arr[], int n) { unordered_map<string, int> freq; unordered_map<string, int> occurence; int max = 0; string result; int k = 1; for (int i = 0; i < n; i++) { if (occurence.count(arr[i]) > 0) { continue; } occurence[arr[i]] = k++; } for (int i = 0; i < n; i++) { freq[arr[i]]++; if (max <= freq[arr[i]]) { if (max < freq[arr[i]]) { max = freq[arr[i]]; result = arr[i]; } else { if (occurence[result] < occurence[arr[i]]) { max = freq[arr[i]]; result = arr[i]; } } } } return result; }};int main(){ string arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = sizeof(arr) / sizeof(arr[0]); Solution obj; cout << obj.mostFrequentWord(arr, n) << endl; return 0;} |
Java
import java.util.*;class GFG { // User function template for Java // Function to find most frequent word in an array of // Strings. String mostFrequentWord(String arr[], int n) { HashMap<String, Integer> freq = new HashMap<>(); HashMap<String, Integer> occurence = new HashMap<>(); int max = 0; String result = ""; int k = 1; for (int i = 0; i < n; i++) { if (occurence.containsKey(arr[i])) { continue; } occurence.put(arr[i], k); k++; } for (int i = 0; i < n; i++) { if (freq.containsKey(arr[i])) { freq.put(arr[i], freq.get(arr[i]) + 1); } else freq.put(arr[i], +1); if (max <= freq.get(arr[i])) { if (max < freq.get(arr[i])) { max = freq.get(arr[i]); result = arr[i]; } else { if (occurence.get(result) < occurence.get(arr[i])) { max = freq.get(arr[i]); result = arr[i]; } } } } return result; } public static void main(String[] args) { String arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = arr.length; GFG obj = new GFG(); System.out.print(obj.mostFrequentWord(arr, n) + "\n"); }}// This code is contributed by Rajput-Ji |
Python3
# Function to find most frequent word# in an array of strings.def mostFrequentWord(arr, n): freq = dict() occurence = dict() max = 0 result = "" k = 1 for i in range(0, n): if arr[i] in occurence.keys(): continue occurence[arr[i]] = k k += 1 for i in range(0, n): if arr[i] in freq.keys(): freq[arr[i]] += 1 else: freq[arr[i]] = 1 if max <= freq[arr[i]]: if max < freq[arr[i]]: max = freq[arr[i]] result = arr[i] else: if occurence[result] < occurence[arr[i]]: max = freq[arr[i]] result = arr[i] return resultif __name__ == "__main__": arr = ['geeks', 'for', 'geeks', 'a', 'portal', 'to', 'learn', 'can', 'be', 'computer', 'science', 'zoom', 'yup', 'fire', 'in', 'be', 'data', 'geeks'] n = len(arr) print(mostFrequentWord(arr, n), end='') print("\n", end='')# This code is contributed by Aarti_Rathi |
C#
// C# Program for the above approachusing System;using System.Collections;using System.Collections.Generic;class Solution { // Function to find most frequent word // in an array of strings. static string mostFrequentWord(string[] arr, int n) { Dictionary<string, int> freq = new Dictionary<string, int>(); Dictionary<string, int> occurence = new Dictionary<string, int>(); int max = 0; string result = ""; int k = 1; for (int i = 0; i < n; i++) { if (occurence.ContainsKey(arr[i])) { continue; } occurence[arr[i]] = k; k++; } for (int i = 0; i < n; i++) { if (freq.ContainsKey(arr[i])) { freq[arr[i]] = freq[arr[i]] + 1; } else { freq.Add(arr[i], 1); } if (max <= freq[arr[i]]) { if (max < freq[arr[i]]) { max = freq[arr[i]]; result = arr[i]; } else { if (occurence[result] < occurence[arr[i]]) { max = freq[arr[i]]; result = arr[i]; } } } } return result; } public static void Main() { string[] arr = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = arr.Length; Console.Write(mostFrequentWord(arr, n)); }}// This code is contributed by Samim Hossain Mondal. |
geeks
Time complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(N)
Most frequent word in an array of strings By Using single Hashmap:
The idea is to use a Hashmap to store the frequency of the words and find the word with the maximum frequency from the hashmap.
Follow the below steps to Implement the idea:
- Initialize a HashMap to store the frequency of the words.
- Traverse a loop from 1 till N
- Increment the count of current word in the Hashmap.
- Initialize key = “” and value = 0
- Traverse the Hashmap
- If the frequency of the current word is greater than value
- Update value to frequency of current character
- Update key as the current word
- If the frequency of the current word is greater than value
- return key.
Below is the implementation of the above approach.
C++
// c++ implementation// Function returns word with highest frequency#include <bits/stdc++.h>using namespace std;// Function returns word with highest frequencystring findWord(vector<string> arr){ // Create HashMap to store word and it's frequency unordered_map<string, int> hs; // Iterate through array of words for (int i = 0; i < arr.size(); i++) { hs[arr[i]]++; } string key = ""; int value = 0; for (auto me : hs) { // Check for word having highest frequency if (me.second > value) { value = me.second; key = me.first; } } // Return word having highest frequency return key;}int main(){ vector<string> arr{ "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; string sol = findWord(arr); // Print word having highest frequency cout << sol << endl;}// This code is contributed by Aarti_Rathi |
Java
// Java implementationimport java.util.*;class GKG { // Function returns word with highest frequency static String findWord(String[] arr) { // Create HashMap to store word and it's frequency HashMap<String, Integer> hs = new HashMap<String, Integer>(); // Iterate through array of words for (int i = 0; i < arr.length; i++) { // If word already exist in HashMap then // increase it's count by 1 if (hs.containsKey(arr[i])) { hs.put(arr[i], hs.get(arr[i]) + 1); } // Otherwise add word to HashMap else { hs.put(arr[i], 1); } } // Create set to iterate over HashMap Set<Map.Entry<String, Integer> > set = hs.entrySet(); String key = ""; int value = 0; for (Map.Entry<String, Integer> me : set) { // Check for word having highest frequency if (me.getValue() > value) { value = me.getValue(); key = me.getKey(); } } // Return word having highest frequency return key; } // Driver code public static void main(String[] args) { String arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; String sol = findWord(arr); // Print word having highest frequency System.out.println(sol); }}// This code is contributed by Divyank Sheth |
C#
// C# implementationusing System;using System.Collections.Generic;class GFG { // Function returns word with highest frequency static String findWord(String[] arr) { // Create Dictionary to store word // and it's frequency Dictionary<String, int> hs = new Dictionary<String, int>(); // Iterate through array of words for (int i = 0; i < arr.Length; i++) { // If word already exist in Dictionary // then increase it's count by 1 if (hs.ContainsKey(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } // Otherwise add word to Dictionary else { hs.Add(arr[i], 1); } } // Create set to iterate over Dictionary String key = ""; int value = 0; foreach(KeyValuePair<String, int> me in hs) { // Check for word having highest frequency if (me.Value > value) { value = me.Value; key = me.Key; } } // Return word having highest frequency return key; } // Driver code public static void Main(String[] args) { String[] arr = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; String sol = findWord(arr); // Print word having highest frequency Console.WriteLine(sol); }}// This code is contributed by Rajput-Ji |
Javascript
<script> // JavaScript implementation // Function returns word with highest frequency function findWord(arr) { // Create Dictionary to store word // and it's frequency var hs = {}; // Iterate through array of words for (var i = 0; i < arr.length; i++) { // If word already exist in Dictionary // then increase it's count by 1 if (hs.hasOwnProperty(arr[i])) { hs[arr[i]] = hs[arr[i]] + 1; } // Otherwise add word to Dictionary else { hs[arr[i]] = 1; } } // Create set to iterate over Dictionary var Key = ""; var Value = 0; for (const [key, value] of Object.entries(hs)) { // Check for word having highest frequency if (value > Value) { Value = value; Key = key; } } // Return word having highest frequency return Key; } // Driver code var arr = [ "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks", ]; var sol = findWord(arr); // Print word having highest frequency document.write(sol); </script> |
geeks
Time Complexity: O(N), where N is the size of the given array.
Auxiliary Space: O(N)
Most frequent word in an array of strings By Using Trie data structure:
The Idea is to store the count of each element and a string variable to keep track of the most occuring element in the array.
Follow the below steps to Implement the idea:
- Initialize a Trie root.
- Traverse the words in the given array
- Insert the word in Trie
- Increment the count of current word by 1
- If the maxCount < count of current word
- Update maxCount to current word count.
- Update maxFrequentString as the current word.
- Print maxFrequentString and maxCount.
Below is the implementation of the above approach.
C++
// CPP code to find most frequent word in// an array of strings#include <bits/stdc++.h>using namespace std;/*structing the trie*/struct Trie { string key; int cnt; unordered_map<char, Trie*> map;};/* Function to return a new Trie node */Trie* getNewTrieNode(){ Trie* node = new Trie; node->cnt = 0; return node;}/* function to insert a string */void insert(Trie*& root, string& str, int& maxCount, string& mostFrequentString){ // start from root node Trie* temp = root; for (int i = 0; i < str.length(); i++) { char x = str[i]; /*a new node if path doesn't exists*/ if (temp->map.find(x) == temp->map.end()) temp->map[x] = getNewTrieNode(); // go to next node temp = temp->map[x]; } // store key and its count in leaf nodes temp->key = str; temp->cnt += 1; if (maxCount < temp->cnt) { maxCount = temp->cnt; mostFrequentString = str; }}void mostFrequentWord(string arr[], int n){ // Insert all words in a Trie Trie* root = getNewTrieNode(); int cnt = 0; string key = ""; for (int i = 0; i < n; i++) insert(root, arr[i], cnt, key); cout << "The word that occurs most is : " << key << endl; cout << "No of times: " << cnt << endl;}// Driver codeint main(){ // given set of keys string arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; int n = sizeof(arr) / sizeof(arr[0]); mostFrequentWord(arr, n); return 0;} |
Java
import java.util.HashMap;import java.util.Map;public class TrieTest { class TrieNode { Map<Character, TrieNode> children; boolean endOfWord; int count; public TrieNode() { children = new HashMap<>(); endOfWord = false; count = 0; } } private TrieNode root = new TrieNode(); private int maxCount = Integer.MIN_VALUE; private String mostFrequentString; public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { Character ch = word.charAt(i); if (current.children.size() == 0 || (!current.children.containsKey(ch))) { current.children.put(ch, new TrieNode()); } TrieNode child = current.children.get(ch); current = child; } current.endOfWord = true; current.count++; if (maxCount < current.count) { maxCount = current.count; mostFrequentString = word; } } public static void main(String[] args) { String[] words = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; TrieTest test = new TrieTest(); for (String word : words) { test.insert(word); } System.out.println(test.mostFrequentString); System.out.println(test.maxCount); }} |
C#
using System;using System.Collections.Generic;public class TrieTest { public class TrieNode { public Dictionary<char, TrieNode> children; public bool endOfWord; public int count; public TrieNode() { children = new Dictionary<char, TrieNode>(); endOfWord = false; count = 0; } } private TrieNode root = new TrieNode(); private int maxCount = int.MinValue; private String mostFrequentString; public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.Length; i++) { char ch = word[i]; if (current.children.Count == 0 || (!current.children.ContainsKey(ch))) { current.children.Add(ch, new TrieNode()); } TrieNode child = current.children[ch]; current = child; } current.endOfWord = true; current.count++; if (maxCount < current.count) { maxCount = current.count; mostFrequentString = word; } } public static void Main(String[] args) { String[] words = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks" }; TrieTest test = new TrieTest(); foreach(String word in words) { test.insert(word); } Console.WriteLine(test.mostFrequentString); Console.WriteLine(test.maxCount); }}// This code is contributed by Rajput-Ji |
The word that occurs most is : geeks No of times: 3
Time complexity: O(W*L), where W is the number of words in the given array and L is the length of the words.
Auxiliary Space: O(W*L)
This article is contributed by Aarti_Rathi and Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.




Please Login to comment...