Most frequent word in an array of strings
Last Updated :
20 Mar, 2024
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.
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.
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.
OutputThe word that occurs most is : geeks
No of times: 2
Time Complexity: O(N*N*M), when N is the size of the given array and M is the maximum length of a word or string since comparison operator on strings work on O(length_of_string).
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:
// 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
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.
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
Time complexity: O(N*M), where N is the size of the given array and M is the maximum length of a word or string since hashing will work on O(length_of_string) instead of O(1) as in integers.
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
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>
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
Time Complexity: O(N*M), where N is the size of the given array and M is the maximum length of a word or string since hashing will work on O(length_of_string) instead of O(1) as in integers.
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);
}
}
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__
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__
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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem