BudiBadu Logo

Word Frequency Counter

Hash Table Easy 2 views
Like0

Ever had a long list of words and wondered which ones show up the most? In Word Frequency Counter, your mission is to return a map (or dictionary) that tells us exactly how many times each word appears. If a word is there once, its count is one. If it repeats, the count should reflect that accurately!

The "secret sauce" here is a Frequency Map. Instead of searching the entire list every time you hit a new word, you use the map to keep a live tally. Think of it like a smart inventory sheet: you check each item, see if it’s already on your list, and if it is, you just increment its count. This only needs one quick scan of the original list, giving you a lightning-fast O(n) complexity. It’s the absolute gold standard for frequency-counting problems in text processing or data analytics. Whether you're checking song lyrics or research papers, this is your go-to move for rapid analysis!

Examples

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 - Budibadu
Recommendation Algorithm Flow for Word Frequency Counter - Budibadu

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