Word Frequency Counter (String)
Given a string of words separated by spaces, count how many times each word appears. Return an object/map where keys are words and values are their frequencies.
For example, "the cat and the dog" has frequencies: the=2, cat=1, and=1, dog=1. "hello world hello" has hello=2, world=1. An empty string returns an empty map.
Word frequency counting is a fundamental text analysis task used in search engines (TF-IDF), sentiment analysis, spam detection, and content summarization. It combines string splitting with hash map aggregation.
The solution splits the string into words, iterates through each word, and updates its count in a hash map. The map stores each unique word as a key and its cumulative count as the value.
Edge cases include an empty string (return empty map), a single word (frequency 1), case sensitivity (same word in different cases counts separately), and punctuation attached to words.
Example Input & Output
Count each word occurrence.
Single word repeated three times.
No words means empty map.
Algorithm Flow
Solution Approach
Split the string into words and count each using a hash map.
Split the input on spaces to get an array of words. Loop through each word. For each word, get its current count (defaulting to 0), increment it, and store it back in the map. Return the frequency map.
Time complexity is O(n), space complexity is O(k) where k is the number of unique words.
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.
