![]() |
VOOZH | about |
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.
Table of Content
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.
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)
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.
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)