Code Logo

Word Frequency Counter (String)

Published at16 Mar 2026
Easy 10 views
Like0

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

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 (String)

Solution Approach

Split the string into words and count each using a hash map.

function wordFreq(s)
  freq = empty map
  words = split(s, " ")
  for i = 0 to length(words) - 1
    w = words[i]
    freq[w] = (freq[w] or 0) + 1
  return freq

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

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