VOOZH about

URL: https://www.geeksforgeeks.org/dsa/frequent-word-array-strings/

⇱ Most Frequent word in an array of strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

[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.


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.


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