BudiBadu Logo

Word Frequency Counter

Hash Table Easy 0 views
Like0

Given a list of strings words, return a map where each word is associated with how many times it appears.

This is a direct frequency-counting problem using a hash map. For each word, increment its count.

Return all words with their counts.

Example 1:

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

Example 2:

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

Example 3:

Input: words = []
Output: {}

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