Most frequent word in an array of strings | Practice | GeeksforGeeks

Given an array arr containing N words consisting of lowercase characters. Your task is to find the most frequent word in the array. If multiple words have same frequency, then print the word whose first occurence occurs last in the array as compared to the other strings with same frequency.
Example 1:
Input:
N = 3
arr[] = {geeks,for,geeks}
Output: geeks
Explanation: "geeks" comes 2 times.

Example 2:
Input:
N = 2
arr[] = {hello,world}
Output: world
Explanation: "hello" and "world" both
have 1 frequency. We print world as
its first occurence comes last in the
input array.
Your Task:
Complete mostFrequentWord function which takes array of strings and its length as arguments and returns the most frequent word. The printing is done by the driver code.
Expected Time Complexity: O(N * WORD_LEN).
Expected Auxiliary Space: O(N * WORD_LEN).
0
vinamrajha3 weeks ago
// this problem is supposed to be solved by using trie not by hashmap/unordered_map.

struct trienode{
   trienode *child[26];
   int count;
   bool flag;
   int in;
   trienode(){
       for(int i =0; i<26; ++i) child[i]= NULL;
       count =0;
       flag = false;
   }
};
void insert(string s, trienode *root, int idx){
       trienode *curr= root;
       for(int i =0; i<s.length(); ++i){
           int index = s[i] -'a';
           if(!curr->child[index]) curr->child[index] = new trienode();
           curr = curr->child[index];
       }
       curr->count++;
       if(!curr->flag){ 
           curr->in = idx;
           curr->flag = true;
       }
   }
   
   trienode *search(string s, trienode *root){
       trienode *curr = root;
       for(int i =0; i<s.length(); ++i){
           int index = s[i]-'a';
           curr = curr->child[index];
       }
       return curr;
   }
   
   string mostFrequentWord(string arr[], int n) 
   {
       // code here
       trienode *root = new trienode();
       int maxi = INT_MIN;
       string ans;
       int idx;
       for(int i =0; i<n; ++i) insert(arr[i], root, i);
       for(int i =0; i<n; ++i){
           trienode *curr = search(arr[i], root);
           if(maxi<curr->count){
               maxi = curr->count;
               ans = arr[i];
               idx = curr->in;
           }else if(maxi == curr->count){
               if(idx<curr->in){
                   ans = arr[i];
                   idx  = curr->in;
               }
           }
       }
       return ans;
   }
0
rajbhargavp1 month ago
from collections import Counter as cclass Solution:      #Function to find most frequent word in an array of strings.   def mostFrequentWord(self,arr,n):       # code here       d=[]       for i in range(n):           if arr[i] not in d:               d.append(arr[i])       a=c(arr)       d.reverse()       d.sort(key=lambda x:a[x] ,reverse=True)       return d[0]       
+1
neeramrutia2 months ago
int max=0;       HashMap<String,Integer> hm=new HashMap<>();       int i;       for(i=0;i<n;i++)       {           if(!hm.containsKey(arr[i]))           {               hm.put(arr[i],1);           }           else           {               hm.put(arr[i],hm.get(arr[i])+1);           }       }       String ans="";       for(i=0;i<n;i++)       {           if(hm.get(arr[i])>=max)           {               max=hm.get(arr[i]);                ans=arr[i];                hm.put(arr[i],0);           }       }       return ans;
0
rahulagarwal11262 months ago
Java Solution 
Runtime: 0.5s
class pair{
    String s;
    int index;
    pair(String s,int index){
        this.s=s;
        this.index=index; 
    }
}

class Solution
{
    //Function to find most frequent word in an array of strings.
    public String mostFrequentWord(String arr[],int n)
    {
        Map<String,Integer>mp=new HashMap<>();
        int maxcount=0;
        for(int i=0;i<n;i++){
            mp.put(arr[i],mp.getOrDefault(arr[i],0)+1); // count the occurences of each String
            maxcount=Math.max(maxcount,mp.get(arr[i])); //maximum count among all occurences
        }
        PriorityQueue<pair>pq=new PriorityQueue<>(new Comparator<pair>(){
            public int compare(pair a, pair b){
                return b.index-a.index; //sorting accoring to maxindex
            }
        }); 
        for(int i=0;i<n;i++){
            if(mp.containsKey(arr[i]) && mp.get(arr[i])==maxcount){
                pq.offer(new pair(arr[i],i));
                mp.remove(arr[i]);
            }
        }
        return pq.poll().s;
        
    }

}
0
neerajsingh130619993 months ago
c++ O(n) simple solution using map
string mostFrequentWord(string arr[], int n)    {       // code here       vector<string> v;       map<string,int> m;       for(int i=0;i<n;i++)       {           if(m.count(arr[i])>0)           m[arr[i]]++;           else           {           m[arr[i]]=1;           v.push_back(arr[i]);           }       }       string s;       int m1=0;       for(int i=0;i<v.size();i++)       {           if(m[v[i]]>=m1)           {               s=v[i];               m1=m[v[i]];           }       }       return s;   }
0
ag14715883 months ago
Java Solution:- 
Runtime: 0.6
 
public static String mostFrequentWord(String arr[],int n)
   {
       HashMap<String,Integer> map = new HashMap<>();
       
       for(int i=0; i<n; i++){
           map.put(arr[i], map.getOrDefault(arr[i], 0)+1 );
       }
       
       int max = Integer.MIN_VALUE;
       String s = "";
       
       for(int i=0; i<n; i++){
           if( map.get(arr[i]) >= max ){
               max = map.get(arr[i]);
               s = arr[i];
               map.put( arr[i],0 );
           }
       }
       return s;
   }
 
-1
kaditya213 months ago
Java Solution:-
 
class Solution{   //Function to find most frequent word in an array of strings.   public String mostFrequentWord(String arr[],int n)   {       Trie trie = new Trie();       for(int i=0; i<n; i++){           trie.insert(arr[i],i);       }              for(String s: arr){           trie.mostFrequent(s);       }              return trie.mostFrequentWord;   }   
}
class Trie{   private class TrieNode{       TrieNode children [];       boolean isEndWord;       int count;       int index = -1;              TrieNode(){           children = new TrieNode[26];           isEndWord = false;           count =0;       }   }      String mostFrequentWord ="";   int maxCount =Integer.MIN_VALUE;       TrieNode root;      Trie(){       root = new TrieNode();   }      public void insert(String key, int position){       TrieNode pointer = root;              for(int i=0; i<key.length(); i++){           int index = key.charAt(i) -'a';           if(pointer.children[index] == null){               pointer.children[index] = new TrieNode();           }           pointer = pointer.children[index];       }              pointer.isEndWord = true;       pointer.count++;              if(pointer.index == -1){           pointer.index =position;       }              if(maxCount < pointer.count){           maxCount = pointer.count;       }   }      int idx =-1;         public void mostFrequent(String key){       TrieNode pointer = root;              for(int i=0; i<key.length(); i++){           int index = key.charAt(i) -'a';           if(pointer.children[index] == null){               pointer.children[index] = new TrieNode();           }           pointer = pointer.children[index];       }              if(pointer.count == maxCount && pointer.index>idx){           mostFrequentWord=key;           idx = pointer.index;       }   }         } 
+2
mr_coder99334 months ago
//using unordered_map C++ 0.1
string mostFrequentWord(string arr[], int n) 
    {
        unordered_map<string,int> m;
        for(int i=0;i<n;i++)
        {
            m[arr[i]]++;
        }
        int Max=INT_MIN;
        string s="";
        for(int i=0;i<n;i++)
        {
         	if(m[arr[i]]>=Max)
            {
                Max=m[arr[i]];
                s=arr[i];
                m[arr[i]]=0;   
            }
        }
        return s;
    }
+4
saiabhiteja5 months ago
using trie data structure
with functions
1.insert
2.countwordsequalto(frequency)
3.getting_start_index(for getting starting index)
 
struct node{   node* links[26];   int endwith=0;   int start_index = -1;
   node(){       for(int i = 0;i<26;i++){           links[i] = nullptr;       }   }
   bool iscontains(char ch){       //checking wether the charcter is already there are not       return (links[ch-'a'] != NULL) ;
   }
   void put(char ch,node* Node){       links[ch-'a'] = Node ;   }
   node* get(char ch){       //for getting particular link        return links[ch-'a'];   }
   void increaseend(){       endwith++;   }      void decreaseend(){       endwith--;   }      void set_start_index(int i){       start_index = i;   }      int getendswith(){       return endwith ;   }   int get_start_index(){       return start_index ;   }
};class trie{   private:   node* root ;   public:   trie(){       //intilisation       root = new node();   }
   void insert(string s,int ind){       //inserting function       node* temp = root ;       for(int i = 0;i<s.size();i++){           if(!temp->iscontains(s[i])){               temp->put(s[i],new node());           }           temp = temp->get(s[i]);       }       temp->increaseend();       if(temp->get_start_index() == -1){           temp->set_start_index(ind) ;       }   }
   int countwordsequalto(string s){       //for getting frequency       node* temp = root;       for(int i = 0;i<s.size();i++){           if(!temp->get(s[i])){               return 0;           }           temp = temp->get(s[i]);       }       return temp->getendswith();   }      int get_starting_index(string s){       //for getting starting index       node* temp = root;       for(int i = 0;i<s.size();i++){           if(!temp->get(s[i])){               return 0;           }           temp = temp->get(s[i]);       }       return temp->get_start_index();          }};class Solution{   public:   //Function to find most frequent word in an array of strings.   string mostFrequentWord(string arr[], int n)    {      trie t;      for(int i = 0;i<n;i++){          t.insert(arr[i],i);      }      int fre = -1;      string ans = "";      for(int i = 0;i<n;i++){          int x = t.countwordsequalto(arr[i]);          int c = t.get_starting_index(arr[i]);          if(x>fre){              fre = x;              ans = arr[i];          }          else if(x == fre){
// for getting last occurrence of same frequency              int c2 = t.get_starting_index(ans);              if(c>c2){                  ans = arr[i];              }          }      }      return ans;   }};
0
adarsh0086 months ago
string mostFrequentWord(string arr[], int n)    {       // code here       string res;              unordered_map<string,int> freq;       unordered_set<string> s;       for(int i=0;i<n;i++)       {           freq[arr[i]]++;       }              res=arr[0];       int res_freq=freq[arr[0]];       s.insert(arr[0]);              for(int i=1;i<n;i++)       {           if(freq[arr[i]]>=res_freq && s.find(arr[i])==s.end())           {               res=arr[i];               res_freq=freq[arr[i]];               s.insert(arr[i]);           }       }              return res;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.