Problem overview
The method letterCount receives a string word and returns a scala.collection.mutable.Map[Char, Int]: each letter of the word is a key, and its value is how many times it appears. The order of entries doesn't matter, and letters that don't appear have no entry.
For "banana" the map has three entries: b maps to 1, a to 3 and n to 2. The keys are Char values (single characters in single quotes, like 'b'), not one-letter strings.
Approach
This is a counting dictionary. Start with an empty map and visit each letter once. If the letter is already a key, add 1 to its count. If not, this is its first appearance, so its count starts at 1.
Step by step
- Create the map.
val counts = scala.collection.mutable.Map[Char, Int]()is empty and can change. - Loop over the letters. A
forloop over aStringvisits its characters one at a time, each aChar. - Known letter. If
counts.contains(letter), setcounts(letter)tocounts(letter) + 1. - New letter. In the
else, setcounts(letter) = 1. - Return the map after the loop.
The solution in Scala
class Solution {
def letterCount(word: String): scala.collection.mutable.Map[Char, Int] = {
val counts = scala.collection.mutable.Map[Char, Int]()
for (letter <- word) {
if (counts.contains(letter)) {
counts(letter) = counts(letter) + 1
} else {
counts(letter) = 1
}
}
return counts
}
}
- Parentheses read and write.
counts(letter)reads a value, andcounts(letter) = 1writes one, adding the key if it isn't there. Scala maps use parentheses, not square brackets. - A missing key throws. Reading
counts('z')when'z'isn't a key throws aNoSuchElementExceptionwith the messagekey not found: z. That is why the code checkscontainsfirst. - Safer reads.
counts.get('z')returns anOption, which isNonefor a missing key, andcounts.getOrElse('z', 0)gives 0. With it, the loop body could be the single linecounts(letter) = counts.getOrElse(letter, 0) + 1. For"aab"it givesamapped to 2 andbto 1. - Printing order. A mutable map's entries print in hash order, not in the order of insertion.
letterCount("banana")prints asHashMap(a -> 3, b -> 1, n -> 2). The lesson's tests ignore the order.
Char keys, not String keys
Looping over a String gives Char values, and the map type Map[Char, Int] is written to match. A Char is a single character in single quotes, 'a', while "a" is a one-character String. They are different types, so counts("a") on this map doesn't compile: the compiler reports Found: ("a" : String) and Required: Char. Use counts('a'), which reads 1 when the map holds a -> 1.
The pattern itself, count by key with a first-time branch, appears again and again: counting words, counting numbers, grouping. Once it is familiar, only the key type changes.
Following the loop
Here is the map after each letter of "banana". The entry order is the one Scala prints, which is not the order of the letters:
| letter | counts afterwards |
|---|---|
| b | HashMap(b -> 1) |
| a | HashMap(a -> 1, b -> 1) |
| n | HashMap(a -> 1, b -> 1, n -> 1) |
| a | HashMap(a -> 2, b -> 1, n -> 1) |
| n | HashMap(a -> 2, b -> 1, n -> 2) |
| a | HashMap(a -> 3, b -> 1, n -> 2) |
Edge cases and common mistakes
- Reading before setting. Doing
counts(letter) += 1for a letter that isn't a key yet throws, so the first appearance needs its own branch (orgetOrElse). - Using an immutable
Map. The defaultMapcan't be changed withcounts(letter) = 1. The type has to be themutableone. - Single letter.
"a"gives one entry,amapped to 1. - Counting only letters that appear. The map has no entries for absent letters, so asking about one needs
getOrElse.
Testing
"banana"givesHashMap(a -> 3, b -> 1, n -> 2)."hello"givesHashMap(e -> 1, h -> 1, l -> 2, o -> 1)."a"givesHashMap(a -> 1).
