Problem overview
The method wordFrequency receives a string, sentence, made of lower-case words separated by single spaces. It returns a HashMap<String, Integer> where each distinct word is a key and its value is how many times the word appears.
For "the cat and the hat" the result is {the=2, and=1, cat=1, hat=1}: "the" appears twice and every other word once. For "go go go" it is {go=3}, one key with the value 3. A sentence of one word, "hello", gives {hello=1}. The order of the entries doesn't matter.
Approach: split, then count
There are two jobs. First, turn the sentence into separate words. Second, count them with a map, the same way you count letters of a word: a word already in the map has its count raised by one, and a new word enters with 1.
The first job is one method call. sentence.split(" ") cuts the string at every space and returns a String[]. For "the cat" it returns an array with the two elements the and cat. Because the lesson guarantees single spaces between words and no other characters, each piece is exactly one word.
Step by step
- Split the sentence into a
String[]namedwords. - Create the empty map.
HashMap<String, Integer> counts = new HashMap<>();holds the words as keys and the counts as values. Nothing has been counted yet. - Loop over the words with an enhanced
forloop, oneString wordper pass. - Known word: if
counts.containsKey(word), put it back withcounts.get(word) + 1.puton an existing key replaces the old value. - New word: in the
else, put it with the value 1. - Return the map after the loop.
The solution in Java
class Solution {
public HashMap<String, Integer> wordFrequency(String sentence) {
String[] words = sentence.split(" ");
HashMap<String, Integer> counts = new HashMap<>();
for (String word : words) {
if (counts.containsKey(word)) {
counts.put(word, counts.get(word) + 1);
} else {
counts.put(word, 1);
}
}
return counts;
}
}
Java details worth knowing:
splittakes a pattern. The argument is a regular expression. A single space has no special meaning in one, so" "works exactly as it reads. Characters such as.or|do have special meanings and would need escaping.- Why not call
getdirectly.getreturnsnullfor a missing key, and adding 1 tonullthrows aNullPointerException. ThecontainsKeycheck avoids it.counts.put(word, counts.getOrDefault(word, 0) + 1)is a compact alternative. - String keys compare by content. A
HashMapfinds keys withequalsandhashCode, so two differentStringobjects holding the same characters are the same key. You don't need to think about==here. - The printed form. A map prints as
{key=value, ...}, with no quotes around the words. The order is up to theHashMap.
Tracing the first example
This is the map after each word of "the cat and the hat" has been handled:
the -> {the=1}
cat -> {the=1, cat=1}
and -> {the=1, and=1, cat=1}
the -> {the=2, and=1, cat=1}
hat -> {the=2, and=1, cat=1, hat=1}
Only the second "the" finds its key already present and raises the count to 2. Every other word creates a new entry.
Reading the result
Once you have the map, get answers "how many times?" for one word. On the first example, get("the") is 2, and get("dog") is null, because a word that never appeared has no entry. To go through every entry, loop over entrySet() and read getKey() and getValue() from each one.
Words are compared exactly. The statement promises lower case, but for a sentence like "The the" the map is {The=1, the=1}: two different keys. Calling toLowerCase() on the sentence first would merge them.
Complexity
Time: O(n) for a sentence of n characters. Splitting reads the string once, and each word then costs a constant number of map operations on average, plus the time to hash the word, which depends on its length.
Space: O(n) in the worst case, for the array of words and the map, which has an entry per distinct word.
Why a map and not a list
You could keep a list of words and, for each new word, scan the list to find it. That makes every word cost time proportional to the number of different words so far. A HashMap finds a key directly from its hash code, so a lookup doesn't grow with the size of the map in the typical case. For a long text, the difference is large.
The same shape of solution counts anything you can split into pieces: split on a comma to count items in a list, or split a log line on spaces to count its fields. Only the argument of split and the key type of the map change.
Edge cases and common mistakes
- More than one space. The lesson promises single spaces. If a sentence had two in a row,
split(" ")would produce an empty string between them:"a b"gives{=1, a=1, b=1}, with an empty-string key. Splitting on the pattern"\\s+"handles runs of spaces. - Forgetting the
else. Without it, a new word never gets an entry, or every count is reset. - A one-word sentence.
"hello".split(" ")returns an array with one element, so the result is{hello=1}. - Expecting an order. Don't depend on the order of the entries.
Testing
"the cat and the hat"gives{the=2, and=1, cat=1, hat=1}."go go go"gives{go=3}."hello"gives{hello=1}.
