Open In App

Most frequent word in an array of strings

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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 occurring variable
    int freq = 0;
    // res to store the most occurring string in the array of
    // strings
    string res;
 
    // running nested for loops to find the most occurring
    // 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 occurred 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 code
int 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 occurring variable
    int freq = 0;
 
    // res to store the most occurring string in the array of
    // strings
    String res = "";
 
    // running nested for loops to find the most occurring
    // 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 occurred 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 occurring variable
    freq = 0
     
    # res to store the most occurring string in the array of strings
    res = ""
 
    # running nested for loops to find the most occurring
    # 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 occurred 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 keys
arr = [ "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer", "science", "zoom", "yup", "fire", "in", "be", "data", "geeks",]
n = len(arr)
 
# function call
mostFrequentWord(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 occurring
    // variable
    int freq = 0;
    // res to store the most occurring string in the
    // array of strings
    string res = "";
 
    // running nested for loops to find the most
    // occurring 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 occurred 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.


Javascript




function mostFrequentWord(arr, n){
    // freq to store the freq of the most occurring variable
    let freq = 0;
     
    // res to store the most occurring string in the array of
    // strings
    let res = "";
     
    // running nested for loops to find the most occurring
    // word in the array of strings
    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++;
            }
        }
         
        // updating our max freq of occurred string in the
          // array of strings
        if(count>=freq){
            res = arr[i];
            freq = count;
        }
    }
     
    console.log("The word that occurs most is : " + res + "<br>");
    console.log("No of times: " + freq);
}
 
// given set of keys
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);
  
// This code is contributed by lokesh.


Output

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 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:
      • then continue.
    • 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:
    // 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> 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 {
 
    // 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> 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");
    }
}
 
// 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()
    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='')
 
# This code is contributed by Aarti_Rathi


C#




// C# Program for the above approach
 
using 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> 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));
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




    // Function to find most frequent word
    // in an array of strings.
    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++) {
 
            // freq[arr[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));
 
// This code is contributed by garg28harsh.


Output

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
  • 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 frequency
string 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 implementation
import 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


Python3




# Python implementation
 
# Function returns word with highest frequency
def findWord(arr):
   
    # Create HashMap to store word and it's frequency
    hs = {}
 
    # Iterate through array of words
    for i in arr:
        if(i in hs):
            hs[i] += 1
        else:
            hs[i] = 1
    key = ""
    value = 0
    for i in hs:
       
        # Check for word having highest frequency
        if(hs[i] > value):
            value = hs[i]
            key = i
 
    # Return word having highest frequency
    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 word having highest frequency
    print(sol)
     
    # This code is contributed by ajaymakvana


C#




// C# implementation
using 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>


Output

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 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++




// 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 code
int 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);
         
    }
}


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)
 
 
# This code is contributed by akashish__


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


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();
 
// This code is contributed by akashish__


Output

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)



Last Updated : 22 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads