Most Frequent word in an array of strings

Last Updated : 28 May, 2026

You are given a string s that is made up of words separated by spaces. Your task is to find the word with the highest frequency, i.e. it appears the most times in the sentence. If multiple words have maximum frequency, then print the word that occurs first in the sentence.

Examples: 

Input: s = "the devil in the sky"
Output: "the 2"
Explanation: The frequency of "the" is 2, so we return "the" and its frequency "2" i.e., "the 2" .

Input: s = "this is not right"
Output: "this 1"
Explanation: Every word has the frequency of "1", so we return "this 1" as this occurs first in the sentence.

Try It Yourself
redirect icon

[Naive Approach] Using Nested Loops - O(n^2 * m) Time O(n * m) Space

The idea is to split the string into words and, for every word, count its frequency using a nested loop. While counting, maintain the word having maximum frequency and return it along with its count.

C++
#include <iostream>
#include <vector>
using namespace std;

string maximumFrequency(string &s)
{

    vector<string> words;
    string temp = "";

    // Split the string into words
    for (char ch : s)
    {

        if (ch == ' ')
        {
            words.push_back(temp);
            temp = "";
        }
        else
        {
            temp += ch;
        }
    }

    words.push_back(temp);

    int n = words.size();

    string res = "";
    int maxFreq = 0;

    // Traverse every word
    for (int i = 0; i < n; i++)
    {

        int count = 0;

        // Count frequency using nested loop
        for (int j = 0; j < n; j++)
        {

            if (words[i] == words[j])
            {
                count++;
            }
        }

        // Update answer
        if (count > maxFreq)
        {
            maxFreq = count;
            res = words[i];
        }
    }

    return res + " " + to_string(maxFreq);
}

// Driver Code
int main()
{

    string s = "the devil in the sky";

    cout << maximumFrequency(s);

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

public class GfG {
    public static String maximumFrequency(String s) {
        ArrayList<String> words = new ArrayList<>();
        String temp = "";

        // Split the string into words
        for (char ch : s.toCharArray()) {
            if (ch == ' ') {
                words.add(temp);
                temp = "";
            } else {
                temp += ch;
            }
        }

        words.add(temp);

        int n = words.size();

        String res = "";
        int maxFreq = 0;

        // Traverse every word
        for (int i = 0; i < n; i++) {
            int count = 0;

            // Count frequency using nested loop
            for (int j = 0; j < n; j++) {
                if (words.get(i).equals(words.get(j))) {
                    count++;
                }
            }

            // Update answer
            if (count > maxFreq) {
                maxFreq = count;
                res = words.get(i);
            }
        }

        return res + " " + maxFreq;
    }

    // Driver Code
    public static void main(String[] args) {
        String s = "the devil in the sky";
        System.out.println(maximumFrequency(s));
    }
}
Python
def maximumFrequency(s):

    words = s.split()

    res = ""
    maxFreq = 0

    # Traverse every word
    for i in range(len(words)):

        count = 0

        # Count frequency using nested loop
        for j in range(len(words)):

            if words[i] == words[j]:
                count += 1

        # Update answer
        if count > maxFreq:
            maxFreq = count
            res = words[i]

    return res + " " + str(maxFreq)


if __name__ == "__main__":

    s = "the devil in the sky"

    print(maximumFrequency(s))
C#
using System;
using System.Collections.Generic;

public class GfG {
    public static string maximumFrequency(string s)
    {

        List<string> words = new List<string>();
        string temp = "";

        // Split the string into words
        foreach(char ch in s)
        {

            if (ch == ' ') {
                words.Add(temp);
                temp = "";
            }
            else {
                temp += ch;
            }
        }

        words.Add(temp);

        int n = words.Count;

        string res = "";
        int maxFreq = 0;

        // Traverse every word
        for (int i = 0; i < n; i++) {

            int count = 0;

            // Count frequency using nested loop
            for (int j = 0; j < n; j++) {

                if (words[i] == words[j]) {
                    count++;
                }
            }

            // Update answer
            if (count > maxFreq) {
                maxFreq = count;
                res = words[i];
            }
        }

        return res + " " + maxFreq.ToString();
    }

    // Driver Code
    public static void Main()
    {

        string s = "the devil in the sky";

        Console.WriteLine(GfG.maximumFrequency(s));
    }
}
JavaScript
function maximumFrequency(s) {
    let words = s.split(' ');
    let res = '';
    let maxFreq = 0;

    // Traverse every word
    for (let i = 0; i < words.length; i++) {
        let count = 0;

        // Count frequency using nested loop
        for (let j = 0; j < words.length; j++) {
            if (words[i] === words[j]) {
                count++;
            }
        }

        // Update answer
        if (count > maxFreq) {
            maxFreq = count;
            res = words[i];
        }
    }

    return res +'' + maxFreq;
}

// Driver Code
let s = 'the devil in the sky';
console.log(maximumFrequency(s));

Output
the 2

Time Complexity: O(n^2 * m) Here n is total number of words and m is max length of a word.
Space Complexity: O(n * m)

[Expected Approach] Using Hash Map or Dictionary - O(n * m) Time O(n * m) Space

The idea is to split the string into words and use a Hash Map to store the frequency of each word. Then traverse the words again and find the first occurring word having the maximum frequency.

C++
#include <iostream>
#include <vector>
#include <unordered_map>
#include <sstream>
using namespace std;

string maximumFrequency(string &s)
{

    // stringstream to split the given string into words
    istringstream stm(s);

    string word;

    // Vector to store all words
    vector<string> words;

    // Split the string into words
    while (stm >> word)
    {
        words.push_back(word);
    }

    // HashMap to store frequency of words
    unordered_map<string, int> freq;

    // Count frequency of each word
    for (int i = 0; i < words.size(); i++)
    {
        freq[words[i]]++;
    }

    int maxFreq = 0;
    string res = "";

    // Find the first occurring word
    // having maximum frequency
    for (int i = 0; i < words.size(); i++)
    {

        if (freq[words[i]] > maxFreq)
        {
            maxFreq = freq[words[i]];
            res = words[i];
        }
    }

    return res + " " + to_string(maxFreq);
}

// Driver Code
int main()
{

    string s = "the devil in the sky";

    cout << maximumFrequency(s);

    return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class GfG {
    public static String maximumFrequency(String s) {
        // StringTokenizer to split the given string into words
        StringTokenizer stm = new StringTokenizer(s);

        // Array to store all words
        String[] words = new String[stm.countTokens()];
        int i = 0;
        while (stm.hasMoreTokens()) {
            words[i++] = stm.nextToken();
        }

        // HashMap to store frequency of words
        HashMap<String, Integer> freq = new HashMap<>();

        // Count frequency of each word
        for (i = 0; i < words.length; i++) {
            freq.put(words[i], freq.getOrDefault(words[i], 0) + 1);
        }

        int maxFreq = 0;
        String res = "";

        // Find the first occurring word
        // having maximum frequency
        for (i = 0; i < words.length; i++) {
            if (freq.get(words[i]) > maxFreq) {
                maxFreq = freq.get(words[i]);
                res = words[i];
            }
        }

        return res + " " + maxFreq;
    }

    // Driver Code
    public static void main(String[] args) {
        String s = "the devil in the sky";
        System.out.println(maximumFrequency(s));
    }
}
Python
def maximumFrequency(s):

    # Split the given string into words
    words = s.split()

    # Dictionary to store frequency of words
    freq = {}

    # Count frequency of each word
    for word in words:
        if word in freq:
            freq[word] += 1
        else:
            freq[word] = 1

    maxFreq = 0
    res = ""

    # Find the first occurring word
    # having maximum frequency
    for word in words:
        if freq[word] > maxFreq:
            maxFreq = freq[word]
            res = word

    return res + " " + str(maxFreq)


# Driver Code
if __name__ == "__main__":

    s = "the devil in the sky"

    print(maximumFrequency(s))
C#
using System;
using System.Collections.Generic;
using System.Linq;

public class GfG
{
    public static string maximumFrequency(string s)
    {
        // Split the given string into words
        string[] words = s.Split(' ');

        // Dictionary to store frequency of words
        Dictionary<string, int> freq = new Dictionary<string, int>();

        // Count frequency of each word
        foreach (string word in words)
        {
            if (freq.ContainsKey(word))
            {
                freq[word]++;
            }
            else
            {
                freq[word] = 1;
            }
        }

        int maxFreq = 0;
        string res = "";

        // Find the first occurring word
        // having maximum frequency
        foreach (string word in words)
        {
            if (freq[word] > maxFreq)
            {
                maxFreq = freq[word];
                res = word;
            }
        }

        return res + " " + maxFreq;
    }

    // Driver Code
    public static void Main()
    {
        string s = "the devil in the sky";
        Console.WriteLine(maximumFrequency(s));
    }
}
JavaScript
function maximumFrequency(s) {

    // Split the given string into words
    let words = s.split(' ');

    // Object to store frequency of words
    let freq = {};

    // Count frequency of each word
    for (let word of words) {
        if (freq[word]) {
            freq[word]++;
        } else {
            freq[word] = 1;
        }
    }

    let maxFreq = 0;
    let res = "";

    // Find the first occurring word
    // having maximum frequency
    for (let word of words) {
        if (freq[word] > maxFreq) {
            maxFreq = freq[word];
            res = word;
        }
    }

    return res + " " + maxFreq;
}

// Driver Code
let s = "the devil in the sky";
console.log(maximumFrequency(s));

Output
the 2

Time Complexity: O(n * m) Here n is total number of words and m is max length of a word.
Space Complexity: O(n * m)

Comment