Word Frequency Counter
You are given a list of words and need to count how many times each word appears.
The output is not a single number. It is a map or dictionary where each distinct word is a key and its number of occurrences is the value. If a word appears three times, its count should be 3. If the input list is empty, the answer is an empty map.
For example, ["apple","banana","apple"] becomes {"apple":2,"banana":1}. A list like ["a","a","a"] becomes {"a":3}.
So the task is to build a full frequency table for the words that actually appear in the input.
Example Input & Output
Count each word occurrence.
Single word repeated three times.
No words means empty map.
Algorithm Flow

Solution Approach
This is a direct frequency counting problem, and a hash map is exactly the right tool for it. The idea is to use each word as a key and store how many times that word has appeared so far.
We begin with an empty map, for example const freq = {}.
Then we walk through the words list one item at a time. For each word, we check whether it already has a count in the map. If it does not, we start it at 1. If it does, we increase the stored count by one.
In code-like form, the update step is:
That single line handles both cases. A new word starts from 0 and becomes 1, while a repeated word keeps growing.
When the loop finishes, the map already contains the final answer. There is no extra sorting step and no second pass needed, because every occurrence was counted as soon as it was seen.
This approach is efficient because each word is processed once. The time complexity is O(n), where n is the number of words, and the space complexity is O(k), where k is the number of distinct words stored in the final map.
Best Answers
import java.util.*;
class Solution {
public Map<String, Integer> word_frequency_counter(String[] words) {
Map<String, Integer> freq = new HashMap<>();
for (String w : words) freq.put(w, freq.getOrDefault(w, 0) + 1);
return freq;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
