Problem overview
The function letterCount receives a string, word, and returns a map from each letter to the number of times it appears. For "banana" the map holds b with 1, a with 3 and n with 2. A letter that isn't in the word has no entry, and the order of the entries doesn't matter.
Approach: a counting dictionary
A map stores key-value pairs, and counting is one of its classic uses. Each letter is a key, and its value is how many times the loop has seen that letter so far. The loop visits every letter once. A letter seen before gets its count raised by one, and a letter seen for the first time starts at 1.
Step by step
- Create the map.
mutableMapOf<Char, Int>()is empty and can change. The type arguments say that keys areCharand values areInt. Store it in aval: the name stays tied to this map while its entries change. - Loop over the letters. A
forloop over a string visits its characters one at a time, each aChar. - Known letter. If
counts.containsKey(letter), setcounts[letter]to its current value plus 1. - New letter. In the
elsebranch, setcounts[letter] = 1. - Return the map after the loop.
The solution in Kotlin
class Solution {
fun letterCount(word: String): MutableMap<Char, Int> {
val counts = mutableMapOf<Char, Int>()
for (letter in word) {
if (counts.containsKey(letter)) {
counts[letter] = counts[letter]!! + 1
} else {
counts[letter] = 1
}
}
return counts
}
}
Kotlin details worth knowing:
- Assigning with brackets.
counts[letter] = 1adds the key when it's missing and replaces the value when it exists. Both branches use the same syntax. - Why
!!.counts[letter]has the typeInt?, because a missing key givesnull. Adding 1 to a nullable value doesn't compile.!!says "this isn't null", and it is safe here becausecontainsKeyjust confirmed the key. If the value were null,!!would throw an exception. - A shorter form.
counts[letter] = (counts[letter] ?: 0) + 1replaces the wholeifandelse: the Elvis operator?:supplies 0 when the key is missing.counts.getOrDefault(letter, 0) + 1works too. - Keys are
Char, notString. A character literal uses single quotes. With the map above,counts['b']is1andcounts['z']isnull. Asking forcounts["b"]with a string key doesn't compile:
error: type inference failed. The value of the type parameter 'K' must be mentioned in input types (argument types, receiver type, or expected type). Try to specify it explicitly.
- Printing and order.
mutableMapOfkeeps entries in insertion order, soprintlnshows the letters in the order they first appeared. The lesson doesn't depend on that order.
Tracing the loop
For "banana", the map after each letter is:
b -> {b=1}
a -> {b=1, a=1}
n -> {b=1, a=1, n=1}
a -> {b=1, a=2, n=1}
n -> {b=1, a=2, n=2}
a -> {b=1, a=3, n=2}
The first three letters are new, so each goes through the else branch. The last three are repeats and go through the if branch. The same two-branch pattern, check, then increase or start at one, counts anything: words, numbers or any other keys.
Edge cases and common mistakes
- One letter.
"a"gives a map with one entry,awith 1. - Forgetting the
else. Without it, a letter's first appearance is never recorded, so no letter would get a count. - Creating the map inside the loop. Each pass would start from an empty map and discard the earlier counts.
- Counting every letter of the alphabet. Only the letters in the word are keys.
Testing
"banana"gives{b=1, a=3, n=2}."hello"gives{h=1, e=1, l=2, o=1}."a"gives{a=1}.
