← Back to libraryQuestion 98 of 273
⌨️Java CodingIntermediate

Count Word Frequency in a Sentence

📌 Definition:

Count how many times each word occurs in a block of text.

📖 Detailed Explanation:

Normalize (lowercase, strip punctuation), split into words, and aggregate counts in a hash map. Filter out empty tokens from punctuation splits. O(number of words). This naturally leads into "sort the map by frequency" (the next topic).

💻 Solutions:
public static Map<String,Integer> wordFrequency(String text) {
    Map<String,Integer> m = new LinkedHashMap<>();
    for (String w : text.toLowerCase().split("\\W+")) {
        if (!w.isEmpty()) m.merge(w, 1, Integer::sum);
    }
    return m;
}
function wordFrequency(text) {
  const m = {};
  for (const w of text.toLowerCase().split(/\W+/)) {
    if (w) m[w] = (m[w] || 0) + 1;
  }
  return m;
}
import re
from collections import Counter

def word_frequency(text):
    return dict(Counter(re.findall(r'\w+', text.lower())))
🔑 Key Points:
  • Normalize: lowercase, strip punctuation
  • Aggregate counts in a hash map
  • Filter empty tokens
  • O(number of words)
🌍 Real-World Example:

Word/token frequency is the backbone of log analysis — which error or endpoint appears most — and search relevance.

🎯 Scenario-Based Interview Question:

Your counts treat "QA" and "qa." as different words. How do you fix the tokenization?