Code Logo

Word Frequency Counter

Published at16 Mar 2026
Easy 6 views
Like0

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

Example 1
Input
words = ["apple","banana","apple"]
Output
{"apple":2,"banana":1}
Explanation

Count each word occurrence.

Example 2
Input
words = ["a","a","a"]
Output
{"a":3}
Explanation

Single word repeated three times.

Example 3
Input
words = []
Output
{}
Explanation

No words means empty map.

Algorithm Flow

Recommendation Algorithm Flow for Word Frequency Counter
Recommendation Algorithm Flow for Word Frequency Counter

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:

for (const word of words) { freq[word] = (freq[word] || 0) + 1; }

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

java
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;
    }
}