Problem overview
The method letterCount receives a string, word, and returns a HashMap<Character, Integer> that maps each letter of the word to the number of times it appears. Only letters that occur get an entry.
For "banana" the map holds b once, a three times and n twice. Printed, it looks like {a=3, b=1, n=2}. For "hello" it is {e=1, h=1, l=2, o=1}, and for "a" it is {a=1}. The order of the entries doesn't matter: a HashMap doesn't promise any order, so don't rely on the order you see when printing.
Approach: a counting dictionary
A map is the right tool whenever the answer is "how many of each". The key is the thing you count, the letter, and the value is the running total. Read the letters one at a time. A letter you have already seen gets its total raised by one. A new letter gets an entry that starts at 1. At the end, every letter of the word has an entry with its full count.
Step by step
- Create the map.
HashMap<Character, Integer> counts = new HashMap<>();starts empty. Generic types can't be primitives, so the key type isCharacter, the object version ofchar, and the value type isInteger. Java converts betweencharandCharacter, and betweenintandInteger, automatically. - Loop over the characters. A
Stringcan't be used in an enhancedforloop directly.word.toCharArray()returns achar[]with one element per character, and that can be. - Check whether the letter is a key.
counts.containsKey(letter)is true when the letter has been seen before. If so,putthe letter again withcounts.get(letter) + 1.puton an existing key replaces its value. - Otherwise start at 1. In the
elsebranch,counts.put(letter, 1)creates the entry for a first occurrence. - Return the map after the loop.
The solution in Java
class Solution {
public HashMap<Character, Integer> letterCount(String word) {
HashMap<Character, Integer> counts = new HashMap<>();
for (char letter : word.toCharArray()) {
if (counts.containsKey(letter)) {
counts.put(letter, counts.get(letter) + 1);
} else {
counts.put(letter, 1);
}
}
return counts;
}
}
Java details that matter here:
- Why the
elseis needed.getreturnsnullfor a missing key. For"banana",counts.get('z')givesnull. Adding 1 to thatnullwould throw aNullPointerException, because Java tries to unbox it into anint. ThecontainsKeycheck makes suregetonly runs for keys that exist. - A shorter form.
counts.put(letter, counts.getOrDefault(letter, 0) + 1);does the same in one line.getOrDefaultreturns the default, here 0, when the key is missing.counts.getOrDefault('z', 0)on the "banana" map gives0. - Character keys. The loop variable is a primitive
char, and it is boxed into aCharacterwhen it goes into the map. Two boxed characters with the same letter are equal as map keys, so everyalands on the same entry. - No order. Iterating over
countsmay give the entries in an order unrelated to their position in the word. If you need the order of first appearance, use aLinkedHashMap.
Tracing "banana"
This is the map after each letter of "banana" has been handled:
b -> {b=1}
a -> {a=1, b=1}
n -> {a=1, b=1, n=1}
a -> {a=2, b=1, n=1}
n -> {a=2, b=1, n=2}
a -> {a=3, b=1, n=2}
The first a takes the else branch and creates the entry. The second and third take the if branch and raise it to 2 and then 3. The method does nothing more than repeat this decision once per letter.
The merge method is another compact way to write the same update: counts.merge(letter, 1, Integer::sum) stores 1 for a new key and adds 1 to an existing one. On "banana" it also ends with {a=3, b=1, n=2}. The explicit if and else in the lesson show each case separately, which makes the logic easier to follow the first time.
Complexity
Time: O(n) for a word of n letters. Each letter takes a constant number of map operations on average.
Space: O(k), where k is the number of different letters. With lowercase English letters, k is at most 26, however long the word is.
Using the result
The map answers questions about the word directly. After letterCount("banana"), get('a') is 3 and size() is 3, the number of different letters. A letter that isn't in the word gives null from get, so check with containsKey or use getOrDefault before doing arithmetic on the answer.
Edge cases and common mistakes
- Calling
getwithout checking. The first time a letter appears,counts.get(letter) + 1fails with aNullPointerException. - Using
Stringkeys by mistake. The method's return type isHashMap<Character, Integer>. AHashMap<String, Integer>is a different type and won't compile as the return value. - Counting every letter of the alphabet. Only letters that appear are keys. A letter with count 0 shouldn't have an entry.
- Resetting a count. Calling
counts.put(letter, 1)for every letter, without thecontainsKeycheck, leaves every count at 1.
Testing
"banana"gives{a=3, b=1, n=2}."hello"gives{e=1, h=1, l=2, o=1}."a"gives{a=1}.
Printing a map shows key=value pairs in braces. The order you see on your machine may differ from the lists above; the entries are the same.
