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 times
Input: 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++
#include <bits/stdc++.h>
using namespace std;
void mostFrequentWord(string arr[], int n)
{
int freq = 0;
string res;
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = i + 1; j < n; j++) {
if (arr[j] == arr[i]) {
count++;
}
}
if (count >= freq) {
res = arr[i];
freq = count;
}
}
cout << "The word that occurs most is : " << res
<< endl;
cout << "No of times: " << freq << endl;
}
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]);
mostFrequentWord(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void mostFrequentWord(String arr[], int n)
{
int freq = 0 ;
String res = "" ;
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++;
}
}
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)
{
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);
}
}
|
Python3
def mostFrequentWord(arr, n):
freq = 0
res = ""
for i in range ( 0 , n, 1 ):
count = 0
for j in range (i + 1 , n, 1 ):
if arr[j] = = arr[i]:
count + = 1
if count > = freq:
res = arr[i]
freq = count
print ( "The word that occurs most is : " + str (res))
print ( "No of times: " + str (freq))
arr = [ "geeks" , "for" , "geeks" , "a" , "portal" , "to" , "learn" , "can" , "be" , "computer" , "science" , "zoom" , "yup" , "fire" , "in" , "be" , "data" , "geeks" ,]
n = len (arr)
mostFrequentWord(arr, n)
|
C#
using System;
class GFG {
static void mostFrequentWord( string [] arr, int n)
{
int freq = 0;
string res = "" ;
for ( int i = 0; i < n; i++) {
int count = 0;
for ( int j = i + 1; j < n; j++) {
if (arr[j] == arr[i]) {
count++;
}
}
if (count >= freq) {
res = arr[i];
freq = count;
}
}
Console.WriteLine( "The word that occurs most is : "
+ res);
Console.WriteLine( "No of times: " + freq);
}
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;
mostFrequentWord(arr, n);
}
}
|
Javascript
function mostFrequentWord(arr, n){
let freq = 0;
let res = "" ;
for (let i=0;i<n;i++){
let count = 0;
for (let j=i+1;j<n;j++){
if (JSON.stringify(arr[j]) === JSON.stringify(arr[i])){
count++;
}
}
if (count>=freq){
res = arr[i];
freq = count;
}
}
console.log( "The word that occurs most is : " + res + "<br>" );
console.log( "No of times: " + freq);
}
let arr = [ "geeks" , "for" , "geeks" , "a" , "portal" , "to" , "learn" , "can" , "be" , "computer" , "science" , "zoom" , "yup" , "fire" , "in" , "be" , "data" , "geeks" ];
let n = arr.length;
mostFrequentWord(arr, n);
|
OutputThe 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 occurrence 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.
- Traverse a loop from 1 till N
- If the current word exist in the occurrence hashmap:
- Else update occurrence[arr[i]] = k
- Increment k by 1
- 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 occurrence[result] < occurrence[freq[arr[i]]]
- Update max = freq[arr[i]]
- Update result = arr[i]
- Return result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public :
string mostFrequentWord(string arr[], int n)
{
unordered_map<string, int > freq;
unordered_map<string, int > occurrence;
int max = 0;
string result;
int k = 1;
for ( int i = 0; i < n; i++) {
if (occurrence.count(arr[i]) > 0) {
continue ;
}
occurrence[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 (occurrence[result]
< occurrence[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 {
String mostFrequentWord(String arr[], int n)
{
HashMap<String, Integer> freq = new HashMap<>();
HashMap<String, Integer> occurrence
= new HashMap<>();
int max = 0 ;
String result = "" ;
int k = 1 ;
for ( int i = 0 ; i < n; i++) {
if (occurrence.containsKey(arr[i])) {
continue ;
}
occurrence.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 (occurrence.get(result)
< occurrence.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" );
}
}
|
Python3
def mostFrequentWord(arr, n):
freq = dict ()
occurrence = dict ()
max = 0
result = ""
k = 1
for i in range ( 0 , n):
if arr[i] in occurrence.keys():
continue
occurrence[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 occurrence[result] < occurrence[arr[i]]:
max = freq[arr[i]]
result = arr[i]
return result
if __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 = '')
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class Solution {
static string mostFrequentWord( string [] arr, int n)
{
Dictionary< string , int > freq
= new Dictionary< string , int >();
Dictionary< string , int > occurrence
= new Dictionary< string , int >();
int max = 0;
string result = "" ;
int k = 1;
for ( int i = 0; i < n; i++) {
if (occurrence.ContainsKey(arr[i])) {
continue ;
}
occurrence[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 (occurrence[result]
< occurrence[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));
}
}
|
Javascript
function mostFrequentWord(arr, n)
{
const freq = new Map();
const occurrence = new Map();
let max = 0;
let result;
let k = 1;
for (let i = 0; i < n; i++) {
if (occurrence.has(arr[i])== true ) {
continue ;
}
occurrence.set(arr[i],k),k++;
}
for (let i = 0; i < n; i++) {
let x=0;
if (freq.has(arr[i])== true )
x= freq.get(arr[i]);
freq.set(arr[i],x+1);
if (max <= freq.get(arr[i])) {
if (max < freq.get(arr[i])) {
max = freq.get(arr[i]);
result = arr[i];
}
else {
if (occurrence.get(result)
< occurrence.get(arr[i])) {
max = freq.get(arr[i]);
result = arr[i];
}
}
}
}
return result;
}
let arr
= [ "geeks" , "for" , "geeks" , "a" , "portal" ,
"to" , "learn" , "can" , "be" , "computer" ,
"science" , "zoom" , "yup" , "fire" , "in" ,
"be" , "data" , "geeks" ];
let n = arr.length;
console.log(mostFrequentWord(arr, n));
|
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
- return key.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
string findWord(vector<string> arr)
{
unordered_map<string, int > hs;
for ( int i = 0; i < arr.size(); i++) {
hs[arr[i]]++;
}
string key = "" ;
int value = 0;
for ( auto me : hs) {
if (me.second > value) {
value = me.second;
key = me.first;
}
}
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);
cout << sol << endl;
}
|
Java
import java.util.*;
class GKG {
static String findWord(String[] arr)
{
HashMap<String, Integer> hs
= new HashMap<String, Integer>();
for ( int i = 0 ; i < arr.length; i++) {
if (hs.containsKey(arr[i])) {
hs.put(arr[i], hs.get(arr[i]) + 1 );
}
else {
hs.put(arr[i], 1 );
}
}
Set<Map.Entry<String, Integer> > set
= hs.entrySet();
String key = "" ;
int value = 0 ;
for (Map.Entry<String, Integer> me : set) {
if (me.getValue() > value) {
value = me.getValue();
key = me.getKey();
}
}
return key;
}
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);
System.out.println(sol);
}
}
|
Python3
def findWord(arr):
hs = {}
for i in arr:
if (i in hs):
hs[i] + = 1
else :
hs[i] = 1
key = ""
value = 0
for i in hs:
if (hs[i] > value):
value = hs[i]
key = i
return key
if __name__ = = "__main__" :
arr = [ "geeks" , "for" , "geeks" , "a" , "portal" , "to" , "learn" , "can" , "be" , "computer" , "science" , "zoom" , "yup" , "fire" , "in" , "be" , "data" , "geeks" ]
sol = findWord(arr)
print (sol)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static String findWord(String[] arr)
{
Dictionary<String, int > hs
= new Dictionary<String, int >();
for ( int i = 0; i < arr.Length; i++) {
if (hs.ContainsKey(arr[i])) {
hs[arr[i]] = hs[arr[i]] + 1;
}
else {
hs.Add(arr[i], 1);
}
}
String key = "" ;
int value = 0;
foreach (KeyValuePair<String, int > me in hs)
{
if (me.Value > value) {
value = me.Value;
key = me.Key;
}
}
return key;
}
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);
Console.WriteLine(sol);
}
}
|
Javascript
<script>
function findWord(arr) {
var hs = {};
for ( var i = 0; i < arr.length; i++) {
if (hs.hasOwnProperty(arr[i])) {
hs[arr[i]] = hs[arr[i]] + 1;
}
else {
hs[arr[i]] = 1;
}
}
var Key = "" ;
var Value = 0;
for (const [key, value] of Object.entries(hs)) {
if (value > Value) {
Value = value;
Key = key;
}
}
return Key;
}
var arr = [
"geeks" ,
"for" ,
"geeks" ,
"a" ,
"portal" ,
"to" ,
"learn" ,
"can" ,
"be" ,
"computer" ,
"science" ,
"zoom" ,
"yup" ,
"fire" ,
"in" ,
"be" ,
"data" ,
"geeks" ,
];
var sol = findWord(arr);
document.write(sol);
</script>
|
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 occurring 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++
#include <bits/stdc++.h>
using namespace std;
struct Trie {
string key;
int cnt;
unordered_map< char , Trie*> map;
};
Trie* getNewTrieNode()
{
Trie* node = new Trie;
node->cnt = 0;
return node;
}
void insert(Trie*& root, string& str, int & maxCount,
string& mostFrequentString)
{
Trie* temp = root;
for ( int i = 0; i < str.length(); i++) {
char x = str[i];
if (temp->map.find(x) == temp->map.end())
temp->map[x] = getNewTrieNode();
temp = temp->map[x];
}
temp->key = str;
temp->cnt += 1;
if (maxCount < temp->cnt) {
maxCount = temp->cnt;
mostFrequentString = str;
}
}
void mostFrequentWord(string arr[], int n)
{
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;
}
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]);
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);
}
}
|
Python3
class TrieNode:
def __init__( self ):
self .children = {}
self .endOfWord = False
self .count = 0
class TrieTest:
def __init__( self ):
self .root = TrieNode()
self .maxCount = - float ( 'inf' )
self .mostFrequentString = ""
def insert( self , word: str ):
current = self .root
for ch in word:
if ch not in current.children:
current.children[ch] = TrieNode()
current = current.children[ch]
current.endOfWord = True
current.count + = 1
if self .maxCount < current.count:
self .maxCount = current.count
self .mostFrequentString = word
if __name__ = = "__main__" :
words = [ "geeks" , "for" , "geeks" , "a" ,
"portal" , "to" , "learn" , "can" ,
"be" , "computer" , "science" , "zoom" ,
"yup" , "fire" , "in" , "be" ,
"data" , "geeks" ]
test = TrieTest()
for word in words:
test.insert(word)
print (test.mostFrequentString)
print (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);
}
}
|
Javascript
class TrieTest {
constructor() {
this .root = new TrieNode();
this .maxCount = Number.MIN_SAFE_INTEGER;
this .mostFrequentString;
}
insert(word) {
let current = this .root;
for (let i = 0; i < word.length; i++) {
let ch = word[i];
if (current.children.size == 0 || !current.children.has(ch)) {
current.children.set(ch, new TrieNode());
}
let child = current.children.get(ch);
current = child;
}
current.endOfWord = true ;
current.count++;
if ( this .maxCount < current.count) {
this .maxCount = current.count;
this .mostFrequentString = word;
}
}
static main(args) {
let words = [
"geeks" ,
"for" ,
"geeks" ,
"a" ,
"portal" ,
"to" ,
"learn" ,
"can" ,
"be" ,
"computer" ,
"science" ,
"zoom" ,
"yup" ,
"fire" ,
"in" ,
"be" ,
"data" ,
"geeks" ,
];
let test = new TrieTest();
for (let word of words) {
test.insert(word);
}
console.log(test.mostFrequentString);
console.log(test.maxCount);
}
}
class TrieNode {
constructor() {
this .children = new Map();
this .endOfWord = false ;
this .count = 0;
}
}
TrieTest.main();
|
OutputThe 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.