703081. Word with maximum frequency
Easy
Here is the detailed Markdown blog post for the problem:
Word with maximum frequency
Summary
Given an array of words, find the word with the maximum frequency. The frequency of each word is calculated by counting its occurrences in the given array.
Detailed Explanation
The approach to solve this problem involves using a HashMap (or any other data structure that supports constant-time lookups) to store the frequency of each word in the array. Then, we iterate over the map and find the word with the maximum frequency.
Here is a step-by-step breakdown of the solution:
- Initialize an empty HashMap
wordFrequency. - Iterate over the given array of words.
- For each word, check if it already exists in
wordFrequency. If not, add it to the map with a frequency count of 1. If it does exist, increment its frequency by 1. - Once all words have been processed, iterate over
wordFrequencyand find the word with the maximum frequency.
Time complexity: O(n), where n is the number of words in the array.
Space complexity: O(n), as we need to store the frequency count for each unique word.
Optimized Solutions
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static String wordWithMaxFrequency(String[] words) {
Map<String, Integer> wordFrequency = new HashMap<>();
int maxFrequency = 0;
String maxFrequencyWord = "";
for (String word : words) {
wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1);
if (wordFrequency.get(word) > maxFrequency) {
maxFrequency = wordFrequency.get(word);
maxFrequencyWord = word;
}
}
return maxFrequencyWord;
}
}